java - 有没有办法在类型删除后查看我的代码的样子?

标签 java generics

我想知道类型删除后可以使用什么工具查看代码。例如,我想看看以下代码在类型删除后的样子。我知道通用类型信息在最终编译之前被剥离,用对象或边界类型替换类型引用,创建桥方法等。我想在删除过程发生后查看源代码。

  public static void main(String[] args) {
    Predicate<Object> objPredicate = (Object c) -> c.toString().length() > 2 ;
    Predicate<? super Integer> predicate = objPredicate;
    Number n = Integer.valueOf(22);
    System.out.println(predicate.test(n)); //this line does not compile
  }
[如果需要编译代码才能看到删除检查工具在示例上工作,可以省略非编译行或n可以投到 Integer ]

最佳答案

I know that generic type information is stripped prior to final compilation


这并不完全正确,因为删除是编译过程本身的一部分,而不是在编译之前发生的事情。即删除不是发生在源代码上的转换。
因此,没有办法(据我所知)以编程方式获得源代码的转换版本,但是我们可以通过遵循 JLS 4.6 中的规则来弄清楚像这样的简单示例会发生什么情况。 :

Type erasure is a mapping from types (possibly including parameterized types and type variables) to types (that are never parameterized types or type variables). We write |T| for the erasure of type T. The erasure mapping is defined as follows:

  • The erasure of a parameterized type (§4.5) G<T1,...,Tn> is |G|.

  • The erasure of a nested type T.C is |T|.C.

  • The erasure of an array type T[] is |T|[].

  • The erasure of a type variable (§4.4) is the erasure of its leftmost bound.

  • The erasure of every other type is the type itself.

Type erasure also maps the signature (§8.4.2) of a constructor or method to a signature that has no parameterized types or type variables. The erasure of a constructor or method signature s is a signature consisting of the same name as s and the erasures of all the formal parameter types given in s.

The return type of a method (§8.4.5) and the type parameters of a generic method or constructor (§8.4.4, §8.8.4) also undergo erasure if the method or constructor's signature is erased.

The erasure of the signature of a generic method has no type parameters.


对于您的代码片段,我们得到(忽略琐碎的删除):
Predicate<Object> -> Predicate
Predicate<? super Integer> -> Predicate
产量:
public static void main(String[] args) {
    Predicate objPredicate = (Object c) -> c.toString().length() > 2 ;
    Predicate predicate = objPredicate;
    Number n = Integer.valueOf(22);
    System.out.println(predicate.test(n)); //this line does not compile
}
此外,Predicate::test 的删除签名方法是:
boolean test​(Object t)

关于java - 有没有办法在类型删除后查看我的代码的样子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67895684/

相关文章:

带有泛型的 Java 工厂模式

python - 基于属性验证模型

java - GlassFish 4.1 alternatedocroot,访问静态内容

java - 检查Java中对象的子类

c# - 获取 IEnumerable<T> 中 T 的类型

c# - 使用和不使用调试器的反射泛型委托(delegate)的不同行为

c++ - 用于获取 C++ 中所有类型和集合的调试字符串的通用函数

java - 在 Java 中使用朴素贝叶斯 (weka) 进行简单文本分类

java - 如何在http请求中指定范围?

java - 在 Selenium 中选择不同行中的按钮