简体   繁体   English

Java Generics中存储的类型信息在哪里?

[英]Where is the type information stored in Java Generics?

For a generic class, where is the type information stored and how is it enforced at run time.对于通用 class,类型信息存储在哪里以及如何在运行时强制执行。 For example, if I a create a List instance as: List<String> strList = new List<String>();例如,如果我创建一个 List 实例为: List<String> strList = new List<String>(); , this means that 'strList' can be used only with String type. ,这意味着 'strList' 只能与 String 类型一起使用。 But where is that information stored or enforced?但这些信息在哪里存储或执行? Is it at class metadata level or at the instance level?是在 class 元数据级别还是在实例级别? If I create another List instance of type: List<Long> longList = new List<Long>();如果我创建另一个 List 类型的实例: List<Long> longList = new List<Long>(); how does java make sure that 'strList' can only deal with String and 'longList' can only deal with Long. java如何确保'strList'只能处理String,'longList'只能处理Long。 I have the same question for generic methods.我对通用方法有同样的问题。 Each time a generic method is invoked with a different type, how do the type checks work?每次使用不同类型调用泛型方法时,类型检查如何工作?

But where is that information stored or enforced?但这些信息在哪里存储或执行?

It is stored in the source code, and enforced in the compiler.它存储在源代码中,并在编译器中强制执行。

The type checks are easy to break, resulting in runtime failures:类型检查很容易被破坏,导致运行时失败:

List<String> strList = new ArrayList<String>();

List<Integer> intList = (List<Integer>) (List<?>) strList;
intList.add(0);

String str = strList.get(0); // ClassCastException.

However, this is not silently broken: you will get an unchecked cast warning, telling you that the compiler can't be sure whether you are doing something unsafe.然而,这并没有被无声地破坏:你会得到一个未经检查的强制转换警告,告诉你编译器不能确定你是否在做不安全的事情。 The burden is on you either to avoid such unchecked casts (best), or to reason about your code to ensure that the unsafe cast is actually safe.避免这种未经检查的强制转换(最好),或者对代码进行推理以确保不安全的强制转换实际上是安全的,这都是您的负担。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM