The fight against generics and classes

I always struggle with generics. I don’t know why it drives me crazy. I have an old problem, I have 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
    }
}

This does not work . The compiler complains like this:

Cannot create a generic array of Class<? extends Father>

If I changed the string (erroneous) of the array to

private static Class<Father>[] myNiceClasses = new Class<Father>[] {

the same error message appears, but this message is also added:

Type mismatch: cannot convert from Class<Child1> to Class<Father>

The only working version is the line:

private static Class<?>[] myNiceClasses = new Class<?>[] {

This solution is not satisfactory because you cannot do so easily.

So my question is: how to solve this problem? Where is the node in my brain?

+3
source share
6 answers

, java . . ArrayList :

        ArrayList<Class<? extends Father>> myNiceClasses = new ArrayList<Class<? extends Father>>();
        myNiceClasses.add(Child1.class);
        myNiceClasses.add(Child2.class);
+8

, quant_dev, , , . , . , , :

private static Class<? extends Father>[] myNiceClasses =
        (Class<? extends Father>[]) new Class<?>[] {};
+4
+2

- , . , , , Java Generics , . , .

. .

+1

, . Java . ( , , Sun JVM . , , JVM .)

JVM , . , , Class.

, .

To summarize: generics and arrays don't mix.

+1
source

Alternatively, as amit.dev said, you can use a list. In this case, assuming that the myNiceClasses field should be constant, you can use Collections.unmodifiableList to make sure the list cannot be changed:

private static final List<? extends Father> myNiceClasses;
static {
    ArrayList<? extends Father> l = new ArrayList<? extends Father>();
    l.add(Child1.class);
    l.add(Child2.class);
    myNiceClasses = Collections.unmodifiableList(l);
}

This is quite verbose, but has the advantage that it is completely constant and therefore easier to reason about.

0
source

Source: https://habr.com/ru/post/1712173/


All Articles