在Java中输入擦除的例外是什么? [英] What are the exceptions to type erasure in Java?

查看:79
本文介绍了在Java中输入擦除的例外是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上看到它在一些地方提到过,在某些情况下,可以使用反射API来获取有关通用数据类型的信息,这些数据类型我认为会通过类型擦除而丢失。



我正在寻找类型删除未完成的情况的完整列表,即仍然可以通过反射访问某些东西。一个很好的例子列表和相关的反射代码可以在泛型上得到很好的表现。

更新 http://tutorials.jenkov.com/java-reflection/generics.html 就是我正在寻找的例子。

解决方案

我认为这只是归结为:


  • 没有任何对象实例存储任何类型信息。然而,这些类保留了所有的通用签名(否则你不能在编译时有任何泛型类型检查)


    因此,使用反射,您可以读取

    例子:

      class MyList extends ArrayList< MyObject> ; {} 

    List< MyObject> x = new MyList();

    反射会告诉你这是一个MyObject的列表(因为这些信息被编译到MyList类中)。



     列表< MyObject> x = new ArrayList< MyObject>(); 

    反射不会告诉你任何有用的东西(因为ArrayList class 一无所知关于MyObject)。


    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.

    解决方案

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

    这篇关于在Java中输入擦除的例外是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆