为什么 Java 编译器会为包私有超类型中定义的公共方法添加可见性桥接方法? [英] Why does the Java compiler add visibility bridge methods for public methods defined in package-private super types?

查看:23
本文介绍了为什么 Java 编译器会为包私有超类型中定义的公共方法添加可见性桥接方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么 Java 编译器会在此处为 foo 方法添加桥接方法:

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 { }
}

foo 方法被编译为SuperClass 类型的public.尽管如此,SubClass 方法将该方法重新定义为通向相同方法的桥梁.我想知道为什么需要这座桥.

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.

推荐答案

添加此桥接方法的理由是 Java 反射 API 中的一个极端情况,如果没有桥接方法会导致 IllegalAccessException正在添加.该错误记录在 Oracle 的错误跟踪器中:

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:

反射调用

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

没有从 SuperClass 之外的其他包中正确处理,没有修复桥接方法,因为 Java 运行时无法确定 foo 方法的调用是合法的.反射处理对方法声明类型的可见性检查,然后会错误地得出该方法不可见且其调用非法的结论.

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.

这篇关于为什么 Java 编译器会为包私有超类型中定义的公共方法添加可见性桥接方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆