Java Generics: Type erasure of other fields in generic class

58 views Asked by At

If I compile the code below with javac Test.java -Xlint:unchecked, the assignment to the variable c4 produces a warning due to type erasure. The types here are insignificant, just examples.

Why does the object reference g3 lose the type information about the member variable Comparator<String> strCmp? And why does not c1 issue the same warning, as the only difference is that the class is not generic?

import java.util.Comparator;

public class Test {

    NormalClass n = new NormalClass();
    Comparator<String> c1 = n.strCmp;

    GenericClass<Long> g1 = new GenericClass<Long>();
    Comparator<String> c2 = g1.strCmp;

    GenericClass<?> g2 = new GenericClass<Long>();
    Comparator<String> c3 = g2.strCmp;

    GenericClass g3 = new GenericClass<Long>();
    Comparator<String> c4 = g3.strCmp;
}

class NormalClass {
    public Object t;
    public Comparator<String> strCmp;
}

class GenericClass<T> {
    public T t;
    public Comparator<String> strCmp;
}
0

There are 0 answers