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

I am wondering why the Java compiler will add a bridge method for the method foohere:

public class Outer {

  class SuperClass {
    public void foo() { }
  }

  public class SubClass extends SuperClass { }
}

The method is foocompiled as publicin a type SuperClass. However, a method SubClassredefines a method as a bridge to the same method. I wonder why this bridge is needed.

+4
source share
1 answer

Rationally adding this bridge method is the cornerstone of the Java reflection API, which calls IllegalAccessExceptionwithout adding the bridge method. The error is described here in the Oracle bug tracker :

Reflective challenge

Subclass.class.getMethod("foo").invoke(new Subclass())

, SuperClass , Java , foo . , , , .

, . , , .

0

Source: https://habr.com/ru/post/1543749/


All Articles