泛型-为什么类类型变量在静态上下文中无效? [英] Generics - Why are Class type variables not valid in static contexts?
问题描述
我正在从一本书中学习Java泛型.该书说类类型变量在静态上下文中无效",并通过以下示例进行解释.
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.
考虑具有类型变量(例如Entry)的泛型类.您不能将类型变量K和V与静态变量或方法一起使用.例如,以下方法不起作用:
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;
}
}
毕竟,类型擦除意味着在擦除的Entry类中只有一个这样的变量或方法,而对于每个K和V都没有一个.
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.
我不理解上面的解释.我也尝试为K创建相同的代码,并且遇到相同的编译错误.为什么上面的代码是非法的?
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 ?
推荐答案
Java泛型设计者选择使用称为类型擦除"的机制来实现它.这意味着像 Entry< String,Integer>
和 Entry< Integer,String>
之类的通用专业并不作为单独的类存在.类型参数被删除.
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.
从 Entry< String,Integer>
和 Entry< Integer,String>
中删除类型参数后,只剩下 Entry
类.
After you erase the type parameters from Entry<String,Integer>
and Entry<Integer,String>
you're left with just the Entry
class.
如果可能有一个像 defaultValue
这样的静态变量,则您希望 Entry< String,Integer> .defaultValue
是一个整数.并且您希望 Entry< Integer,String> .defaultValue
是一个字符串.但是在类型擦除之后,只有一个 Entry
类只有一个 defaultValue
变量,该变量现在必须是Integer和String.这不可能.这就是为什么您不能拥有泛型类型的静态变量.
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.
这篇关于泛型-为什么类类型变量在静态上下文中无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!