简体   繁体   English

在Java中键入擦除有哪些例外?

[英]What are the exceptions to type erasure in Java?

I have seen it mentioned on some places online that in some situations it is possible to use the reflection API to get back information about generic data types which I thought would be lost through type erasure. 我在网上的某些地方看到它提到在某些情况下可以使用反射API来获取有关通用数据类型的信息,我认为这些信息类型会因类型擦除而丢失。

I am looking for complete list of the situations where type erasure is not complete ie something is still accessible via reflection. 我正在寻找类型擦除不完整的情况的完整列表,即仍可通过反射访问某些内容。 A Good list of examples and associated reflection code that can get at the generic types would be excellent. 可以获得泛型类型的示例和相关反射代码的良好列表将是非常好的。

UPDATE http://tutorials.jenkov.com/java-reflection/generics.html had exactly the examples I was looking for. 更新 http://tutorials.jenkov.com/java-reflection/generics.html正好有我想要的例子。

I think it just comes down to this: 我认为这只是归结为:

  • No object instance stores any type information. 没有对象实例存储任何类型信息。

  • The classes, however, retain all their generic signatures (otherwise you could not have any generic type checking at compile time) 但是,这些类保留了所有通用签名(否则在编译时无法进行任何泛型类型检查)

So, using reflection, you can read the generic type information for a given class. 因此,使用反射,您可以读取给定类的泛型类型信息。

Example: 例:

 class MyList extends ArrayList<MyObject>{}

 List<MyObject> x = new MyList();

Reflection will tell you that this is a List of MyObject (because this information is compiled into the MyList class). 反射会告诉你这是一个MyObject的List(因为这个信息被编译成MyList类)。

but

List<MyObject> x = new ArrayList<MyObject>();

Reflection will not tell you anything useful (because the ArrayList class knows nothing about MyObject). 反射不会告诉你任何有用的东西(因为ArrayList 对MyObject一无所知)。

The general idea is that if you create a named or anonymous class that is a subclass of a generic type with particular types for the type parameters, then the subclass is not generic and not subject to type erasure. 一般的想法是,如果您创建一个名称或匿名类,它是具有类型参数的特定类型的泛型类型的子类,则子类不是通用的,不受类型擦除的影响。 Assuming that you can get hold of the Class object for the subclass, you can use reflection on that object to find out what the parameter types are. 假设您可以获取子类的Class对象,则可以对该对象使用反射来查找参数类型。

When you think about it, this is not really an "exception" to the erasure rule. 当你考虑它时,这实际上并不是擦除规则的“例外”。 Rather, it is arranging that the class in question is not generic by explicitly reifying it. 相反,它通过明确地对它进行安排来安排所讨论的类不是通用的。

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

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