package com.logicbig.example.clazz;
import java.util.HashSet;
import java.util.LinkedHashSet;
public class AsSubclassExample {
public static void main(String... args) throws IllegalAccessException, InstantiationException {
Class<LinkedHashSet> lhs = LinkedHashSet.class;
Class<? extends HashSet> hs = lhs.asSubclass(HashSet.class);
System.out.println(hs);
HashSet hashSet = hs.newInstance();
System.out.println(hashSet.getClass());
}
}
Output
class java.util.LinkedHashSet
class java.util.LinkedHashSet
The method safeAsSubClass in following example is ClassCastException safe:
package com.logicbig.example.clazz;
public class AsSubclassExample2 {
public static void main(String... args) {
Class<? extends Shape> r = safeAsSubClass(Circle.class, Shape.class);
System.out.println("Circle as Shape: " + r);
Class<? extends Shape> r2 = safeAsSubClass(Shape.class, Circle.class);
System.out.println("Shape as Circle: " + r2);
Class<?> r3 = safeAsSubClass(Circle.class, Object.class);
System.out.println("Circle as Object: " + r3);
Class<?> r4 = safeAsSubClass(Object.class, Circle.class);
System.out.println("Object as Circle:" + r4);
}
public static <T> Class<? extends T> safeAsSubClass(Class<?> from, Class<T> as) {
if (as.isAssignableFrom(from)) {
return from.asSubclass(as);
}
return null;
}
public static class Shape {
}
public static class Circle extends Shape {
}
}
Output
Circle as Shape: class com.logicbig.example.clazz.AsSubclassExample2$Circle
Shape as Circle: null
Circle as Object: class com.logicbig.example.clazz.AsSubclassExample2$Circle
Object as Circle:null
package com.logicbig.example.clazz;
public class AsSubclassExample3 {
public static void main(String... args) {
Class<Circle> cc = Circle.class;
//now we need to call method workWithShapeClassUtil
Class<? extends Shape> cs = cc.asSubclass(Shape.class);
workWithShapeClassUtil(cs);
}
public static void workWithShapeClassUtil(Class<? extends Shape> cs) {
System.out.println("working with shape instance: " + cs);
}
public static class Shape {
}
public static class Circle extends Shape {
}
}
Output
working with shape instance: class com.logicbig.example.clazz.AsSubclassExample3$Circle