Why does the Java compiler add visibility bridge methods for public methods defined in package-private super types?

空扰寡人 提交于 2019-12-10 17:21:29

问题


I am wondering why the Java compiler would add a bridge method for the foo method here:

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. Nevertheless, the SubClass method redefines the method as a bridge to the very same method. I wonder why this bridge is necessary.


回答1:


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. The bug is documented here in Oracle's bug tracker:

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. 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.



来源:https://stackoverflow.com/questions/24106486/why-does-the-java-compiler-add-visibility-bridge-methods-for-public-methods-defi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!