Java generics – class or class Extend someclass >
I am writing a program that will dynamically create class instances based on user input using java reflection (i.e. class. Forname()) One requirement is that the instance created by my program must extend a class I define, called someclass My question is: should I use bounded generics to store this class type, extend someclass > or simple unbounded generic classes? I found that some java books say that class is one of the good habits of using unbounded wildcards, but I wonder if this applies to my program
If you find that my problem is not clear enough or you need some information, please feel free to let me know
Solution
You should use class to extend someclass > because it is generic
When you call class Forname, check someclass class. Isassignable comes from the new class Otherwise, you should throw an illegalargumentexception or ClassCastException
Edit: alternatively, calling assubclass (someclass. Class) will do this for you
For example:
public SomeClass instantiate(String name) throws ClassNotFoundException,InstantiationException,illegalaccessexception { Class<?> raw = Class.forName(name); //throws ClassCastException if wrong Class<? extends SomeClass> generic = raw.asSubclass(SomeClass.class); // do what you want with `generic` return generic.newInstance(); }