va类型擦除与字段#getGenericType和方法#getG

va类型擦除与字段#getGenericType和方法#getG

本文介绍了Java类型擦除与字段#getGenericType和方法#getGenericReturnType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,泛型是Java的编译时功能,参数化类型信息在编译后的字节码中不存在。我现在已经发现了Field#getGenericType和Method#getGenericReturnType方法,从而打破了我的世界观。请帮助我将它们拼凑在一起。

解决方案

只删除运行时类型的对象。例如:

  Object obj = new ArrayList< String>(); 

obj.getClass()将返回 ArrayList.class 。你甚至可以知道 ArrayList 有一个通用参数。但是无法判断 obj 是否被创建为 ArrayList< String> , ArrayList< ;整型> , ArrayList< Object> , ArrayList 。

静态类型信息仍然存在于类,方法等(尽管不适用于本地)。这只是额外的一点数据作为属性附加在类文件中,并且在运行时可用。想想它与具有运行时保留的注释非常相似。有问题吗?


As I understand them, generics are a compile time feature of Java, and parametrized type information does not exist in the compiled byte code. I have now discovered the Field#getGenericType and Method#getGenericReturnType methods, thusly shattering my world view. Please help me to piece it together.

解决方案

The just runtime types of objects are erased. For instance:

Object obj = new ArrayList<String>();

obj.getClass() will return ArrayList.class. You can even tell that ArrayList has a generic parameter. But there is no way to tell if obj was created as ArrayList<String>, ArrayList<Integer>, ArrayList<Object>, ArrayList (raw), or anything else.

Static type information is still there for class, methods, etc (although not for locals). This is just an extra bit of data appended as attributes in the class file, and available at runtime. Think of it much the same as annotations with runtime retention. Was there a question?

这篇关于Java类型擦除与字段#getGenericType和方法#getGenericReturnType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:17