I am writing a program which will use Java reflection (i.e., Class.forName()
) to dynamically create class instance based on user's input. One requirement is that the instance my program creates must extend one specific Class I defined, called it SomeClass
. My question is: for storing this class type, should I use bounded generic, Class<? extends SomeClass>
, or simply unbounded generic, Class
? I found some Java books say that Class is one of the good practices for using unbounded wildcard generic, but I am wondering whether this apply to the situation in my program.
Please feel free to let me know if you found my question is not clear enough or some information is needed.
You should use
Class<? extends SomeClass>
because that's what generics are for.At the time when you invoke
Class.forName
, check to see if itSomeClass.class.isAssignableFrom
the new class. Otherwise, you should throw anIllegalArgumentException
orClassCastException
.EDIT: Alternatively, calling
asSubclass(SomeClass.class)
will do this for you.For example: