Generics - Why are Class type variables not valid in static contexts?

Java Impatient :

I am learning Java generics from a book. The book says that "Class Type Variables Are Not Valid in Static Contexts" and explains it with the following example.

Consider a generic class with type variables, such as Entry. You cannot use the type variables K and V with static variables or methods. For example, the following does not work:

public class Entry<K, V> {
    // Compiler error - V in static context ("Entry.this' cannot be referenced from a static context")
    private static V defaultValue;

    // Compiler error - V in static context ("Entry.this' cannot be referenced from a static context")
    public static void setDefault(V value) {
        defaultValue = value;
    }
}

After all, type erasure means there is only one such variable or method in the erased Entry class, and not one for each K and V.

I don't understand the above explanation. I tried to create the same code for K also and I got the same compile errors. Why is the above code illegal ?

Joni :

Designers of Java generics chose to implement it using a mechanism called "type erasure". It means that generic specializations like Entry<String,Integer> and Entry<Integer,String> do not exist as separate classes. The type parameters are erased.

After you erase the type parameters from Entry<String,Integer> and Entry<Integer,String> you're left with just the Entry class.

If it were possible to have a static variable like defaultValue you would expect Entry<String,Integer>.defaultValue to be a Integer. And you would expect Entry<Integer,String>.defaultValue to be a String. But after type erasure only one Entry class with only one defaultValue variable, which now has to be both Integer and String. That's impossible. That's why you can't have a static variable of the generic type.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403871&siteId=1