What are the exceptions to type erasure in Java?

2020-04-10 21:57发布

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.

I am looking for complete list of the situations where type erasure is not complete i.e. 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.

2条回答
Root(大扎)
2楼-- · 2020-04-10 22:45

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.

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.

查看更多
可以哭但决不认输i
3楼-- · 2020-04-10 22:53

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).

but

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

Reflection will not tell you anything useful (because the ArrayList class knows nothing about MyObject).

查看更多
登录 后发表回答