I’m always struggling with generics. I don’t know why this makes my go crazy. I have an old problem I’ve got several times.
class Father {
...
}
class Child1 extends Father {
...
}
class Child2 extends Father {
...
}
public class TestClass {
private static Class<? extends Father>[] myNiceClasses = new Class<? extends Father>[] {
Child1.class,
Child2.class
}
}
That does not work. The compiler complains like this:
Cannot create a generic array of Class<? extends Father>
If I change the (faulty) array line to
private static Class<Father>[] myNiceClasses = new Class<Father>[] {
the same error message occurs, but also this message is added:
Type mismatch: cannot convert from Class<Child1> to Class<Father>
The only working version is this line:
private static Class<?>[] myNiceClasses = new Class<?>[] {
This solution is not satisfying, because you cannot cast so easily.
So my question is: How to solve this problem? Where’s the knot in my brain?
This is because java does not support generic array creation. Generics work best with Collections. So you can use ArrayList to solve your problem: