Java Reflection Java Java API
java.lang.Class
public T cast(Object obj)
This method casts an object to the class or interface represented by this Class object.
Class
obj
package com.logicbig.example.clazz;import java.util.HashSet;import java.util.LinkedHashSet;public class CastExample { public static void main(String... args) { LinkedHashSet<String> lhs = new LinkedHashSet<>(); HashSet hs = HashSet.class.cast(lhs); System.out.println(hs.getClass()); }}
class java.util.LinkedHashSet
package com.logicbig.example.clazz;public class CastExample2 { public static void main(String... args) { Sup sup = new Sup(); Sub sub = safeCastTo(sup, Sub.class); System.out.println(sub); Sub sub2 = new Sub(); Sup sup2 = safeCastTo(sub2, Sup.class); System.out.println(sup2); Other other = new Other(); Sup sup3 = safeCastTo(other, Sup.class); System.out.println(sup3); } public static <T> T safeCastTo(Object obj, Class<T> to) { if (obj != null) { Class<?> c = obj.getClass(); if (to.isAssignableFrom(c)) { return to.cast(obj); } } return null; } public static class Sup { } public static class Sub extends Sup { } public static class Other { }}
nullcom.logicbig.example.clazz.CastExample2$Sub@617d72d2null