gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:02:13 24 4
gpt4 key购买 nike

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

  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 parameterizedtypes and type variables) to types (that are never parameterized typesor type variables). We write |T| for the erasure of type T. Theerasure 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com