javajavacjava-bridge-method

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:

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.


Solution

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