javap和泛型'类型擦除 [英] javap and generics' type erasure

查看:104
本文介绍了javap和泛型'类型擦除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Herbert Schilds关于java中的泛型类型擦除。假设在一个类上运行javap应该给我关于在类型擦除之后的公共,包保护和保护字段和方法的字节码信息。然而,我写了下面的类:

  class Ambiguity< T,V extends String> {
T ob1;
V ob2;

void set(T o){
ob1 = o;
}

void set(V o){
ob2 = o;
}
}

并在生成的类文件上运行javap,得到了以下输出:



从Test.java编译

 类歧义< T,V extends java.lang.String> {
T ob1;
V ob2;
Ambiguity();
void set(T);
void set(V);
}

根据我读的内容,我期待这样的输出。 / p>

 编译自Test.java
类歧义< java.lang.Object,java.lang.String> {
java.lang.Object ob1;
java.lang.String ob2;
Ambiguity();
void set(java.lang.Object);
void set(java.lang.String);
}

我在这里错过了什么吗?我应该补充一点,我明白,以上述方式重载方法并不是一个好习惯。



编辑:这似乎是由于新的修复程序的结果javap的。
http://bugs.sun.com/bugdatabase/view_bug.do ?bug_id = 4870651



如果我从JDK 1.6运行javap,我会得到我期望的结果。如果我从最初使用的JDK 1.7 b30运行javap,我会得到带有通用信息的结果。

解决方案

编译时间 - 在生成的字节码中,类会保留所有的通用类型信息。你看到的正是你所期望的。

不同之处在于类型在运行时处被擦除:例如,类的实例 不会知道它的类型参数是 Integer 字符串


I am reading Herbert Schilds about type erasure in generics in java. Supposedly running javap on a class should give me the bytecode information about public, package protected and protected fields and methods after type erasure. However, I wrote the following class:

    class Ambiguity<T, V extends String>{
    T ob1;
    V ob2;

    void set(T o){
        ob1 = o;
    }

    void set(V o){
        ob2 = o;
    }
}

and ran javap on the class file that was generated and got the following output

Compiled from "Test.java"

class Ambiguity<T, V extends java.lang.String> {
  T ob1;
  V ob2;
  Ambiguity();
  void set(T);
  void set(V);
}

I was expecting an output that looked like this based on what I read.

Compiled from "Test.java"
class Ambiguity<java.lang.Object, java.lang.String> {
  java.lang.Object ob1;
  java.lang.String ob2;
  Ambiguity();
  void set(java.lang.Object);
  void set(java.lang.String);
}

Am I missing something here? I should add that I understand that it is not a good practice to overload methods in the above manner. I was just seeing interested in seeing the results of javap under this ambiguity.

EDIT: This seems to be a result of a new fix in javap. http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4870651

If I run javap from JDK 1.6 I get the results as I was expecting. If I run javap from JDK 1.7 b30 which was what I was using initially, I get the result with the generic information.

解决方案

At compile time -- in the generated bytecode -- classes will, yes, retain all of their generic type information. What you've seen is exactly what you should expect.

The difference is that types are erased at runtime: for example, an instance of the class Ambiguity<Integer, String> will not know that its type arguments are Integer and String respectively.

这篇关于javap和泛型'类型擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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