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

查看:49
本文介绍了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 Reflection 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天全站免登陆