为什么这个类型参数保存在字节码中? [英] Why is this type parameter preserved in the bytecode?

查看:86
本文介绍了为什么这个类型参数保存在字节码中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类型删除页面表示


如果类型参数是无界的,则将泛型类型中的所有类型参数替换为它们的边界或对象。因此,生成的字节码仅包含普通的类,接口和方法。

然而,对于以下类:

  public class Foo< E扩展CharSequence> {
public E something;

javap -c Foo print:

  public class Foo< E extends java.lang.CharSequence> {
public E something;



$ b $为什么类型参数没有被绑定(CharSequence)取代,而是保存为E?

解决方案

你打印的不是字节码。这是方法签名。它放在那里,所以编译器可以在编译调用它的其他类时强制执行类型安全。


The type erasure page says that

Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.

However, for the following class:

public class Foo<E extends CharSequence> {
    public E something;
}

javap -c Foo prints:

public class Foo<E extends java.lang.CharSequence> {
  public E something;
}

Why is the type parameter not replaced with the bound (CharSequence), but is preserved as E?

解决方案

What you printed isn't bytecode. It is the method signature. It's put there so the compiler can enforce typesafety when compiling other classes that call it.

这篇关于为什么这个类型参数保存在字节码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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