[英]Why does the Java compiler add visibility bridge methods for public methods defined in package-private super types?
I am wondering why the Java compiler would add a bridge method for the foo
method here: 我想知道为什么Java编译器会在这里为
foo
方法添加一个桥接方法:
public class Outer {
class SuperClass {
public void foo() { }
}
public class SubClass extends SuperClass { }
}
The foo
method is compiled to be public
in the SuperClass
type. foo
方法在SuperClass
类型中编译为public
。 Nevertheless, the SubClass
method redefines the method as a bridge to the very same method. 然而,
SubClass
方法重新定义了该方法作为同一方法的桥梁。 I wonder why this bridge is necessary. 我想知道为什么这座桥是必要的。
The rational for adding this bridge method is a corner-case in the Java reflection API which would cause an IllegalAccessException
without the bridge method being added. 添加此桥接方法的合理性是Java反射API中的一个例子,它会导致
IllegalAccessException
而不添加桥接方法。 The bug is documented here in Oracle's bug tracker : 这个bug记录在Oracle的bug跟踪器中 :
A reflective invocation 反思性的调用
Subclass.class.getMethod("foo").invoke(new Subclass())
was not processed correctly from other packages than that of SuperClass
without the bridge method fix as the Java run time could not figure out that the invocation of the foo
method was legal. 没有桥接方法修复,没有正确处理其他包而不是
SuperClass
包,因为Java运行时无法弄清楚foo
方法的调用是否合法。 The reflection processes visibility checks on a method's declaring type which would then erroneously conclude that the method was not visible and its invocation illegal. 反射处理可见性检查方法的声明类型,然后错误地断定该方法不可见并且其调用非法。
According to the documentation on the ticket, there was no easier work-around. 根据机票上的文档,没有更简单的解决方法。 A non-reflective invocation was however processed normally, even before the bridge method was added.
然而,即使在添加桥接方法之前,也会正常处理非反射调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.