I have the following problem: I want to write a framework that uses java reflection. I get (where) the class name, and I want to load the class and create an instance. As a side restriction, all valid classes belong to a common superclass.
To simplify and simplify, I do not post all of my classes. Instead, I encoded some kind of "MWE" (see below).
What should I do? First I define Stringwhich mimics the name of the loadable class. In my application, I get the name from the XML file. The representing class should be a subclass of this class (here Filein my case I have a whole tree of separate classes). I check if the given name is allowed to a class that is a subclass. If it is, then I would have to make the object an Class<?>object Class<File>. Unfortunately, eclipse (and therefore javac) gives a compilation warning.
In this special case, it is normal to ignore the warning, and I could add an annotation to suppress the warning. Fine. But usually in java there is a cleaner solution to such problems. I could also continue to use Class<?>and later use the type when using the object (see Example for an example).
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectTest extends File
{
private static final long serialVersionUID = 8807535438772463115L;
public ReflectTest()
{
super("","");
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalArgumentException, InvocationTargetException, IllegalAccessException
{
String className = "ReflectTest";
Class<?> clsGen = Class.forName(className);
if(! File.class.isAssignableFrom(clsGen))
{
System.exit(1);
}
Class<File> cls = (Class<File>) clsGen;
File f1 = cls.getConstructor().newInstance();
}
}