简体   繁体   English

为什么Java编译器为package-private超类型中定义的公共方法添加可见性桥接方法?

[英]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.

相关问题 包私有类中的公共方法 - public methods in package-private classes 为什么私有访问方法比package-private更可取? - Why private access for methods is more preferable than package-private? 提供测试包的私有方法? - Providing package-private methods for testing? 访问包私有方法的外部类 - Outside classes accessing package-private methods URLClassLoader和package-private方法的可访问性 - URLClassLoader and accessibility of package-private methods 带/ * package * /后缀的Java包专用可见性成员 - Java package-private visibility members with /*package*/ suffix Java编译器11为什么使用invokevirtual调用私有方法? - Why does the Java compiler 11 use invokevirtual to call private methods? 为什么Android类加载器允许从另一个包反射访问包私有类的公共字段? - Why does Android classloader allow reflective access to the public field of a package-private class from another package? Java中public、protected、package-private和private有什么区别? - What is the difference between public, protected, package-private and private in Java? 对于@Transactional方法,禁用警告“Access可以是包私有” - Disable warning “Access can be package-private” for @Transactional methods
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM