Java泛型相关

字节码对象的三种获取方式

以String为例

Class<? extends String> strCls = "".getClass();
Class<String> strCls2 = String.class;
Class strCls3 = Class.forName("java.lang.String");

System.out.println(strCls.equals(strCls2)); // true
System.out.println(strCls.equals(strCls3)); // true

对于第一种方式:通过一个String实例的getClass方法来获取,这个函数的签名如下:

public final native Class<?> getClass();

但文档中对这个函数的解释如下:

The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:
Number n = 0; 
Class<? extends Number> c = n.getClass();

所以上面就要用Class<? extends String>来接收返回值了。

对于第三种方式 forName的返回值为 Class<?>,这个等价于Class。例如 List 同 List<?> 是一样的。 

三种方式获取到的返回值都是一样的,因为String的字节码对象也就只有一个。

关于泛型信息的获取

List<String> ls = new ArrayList<>();
System.out.println(ls.getClass().equals(ArrayList.class));  // true

由于编译期间存在泛型擦除,所以字节码对象不会因为泛型而出现差异。

1

猜你喜欢

转载自www.cnblogs.com/hellohello/p/10283705.html