
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());
}
}
Output
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 {
}
}
Output
null
com.logicbig.example.clazz.CastExample2$Sub@1e357e9c
null