I'm trying to create an array of classes in Java. Not objects, but classes. Currently I have a class MyBaseClass and I extend three classes MyClass1, MyClass2, and MyClass3 from it. I store these classes to a static array like this:
private static MyBaseClass[] classes = {
new MyClass1(),
new MyClass2(),
new MyClass3()
};
public static MyBaseClass getInstanceOfClass(int index) {
return classes[index];
}
and then I use those methods like this:
try {
MyBaseClass obj = getInstanceOfClass(index).getClass().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
Now I'm wondering if I could do this in an easier way. If I could create an array of classes I might be able to escape the getInstanceOfClass() method and some possible exceptions. I tried doing this:
private static Class<MyBaseClass>[] classes = {
MyClass1.class,
MyClass2.class,
MyClass3.class
};
But this gives me an error "Incompatible types" as MyClass1 is not equal to MyBaseClass. Interestingly enough, this seemingly works:
private static Class<?>[] classes = {
new MyClass1().getClass(),
new MyClass2().getClass(),
new MyClass3().getClass()
};
But the idea of that is horrible and it's even marked by my debugger. So, any better ways of doing this?
Edit:
This works:
private static Class<?>[] classes = {
MyClass1.class,
MyClass2.class,
MyClass3.class
};
But then the result of getInstanceOfClass(index).newInstance(); is an Object so I have to do typecasting. I'm not really sure if that's safe in this case...
Class<?>[]orClass<MyBaseClass>[]with an error. ButClass<? extends MyBaseClass>[]is marked.