Consider the following Java program:
import java.lang.reflect.Method;
public class BridgeTest {
public static class ClassA {
public void foo() {
}
}
protected static class ClassB extends ClassA {
@Override
public void foo() {
}
}
public static class ClassC extends ClassB {
}
public static void main(String[] args) throws Exception {
final Method method = ClassC.class.getMethod("foo");
System.out.println(method + " -> isBridge() = " + method.isBridge());
}
}
The output of this program is:
public void BridgeTest$ClassC.foo() -> isBridge() = true
Looking more closely, javap
reports:
public BridgeTest$ClassC();
...
public void foo();
descriptor: ()V
flags: ACC_PUBLIC, ACC_BRIDGE, ACC_SYNTHETIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: invokespecial #2 // Method BridgeTest$ClassB.foo:()V
4: return
LineNumberTable:
line 15: 0
So clearly the compiler has synthesized the method ClassC.foo()
, which makes sense because otherwise the method you'd get from instrospection is ClassB.foo()
which won't be as usable because it's a member of a non-public class.
That explains the ACC_SYNTHETIC
flag...
But why the ACC_BRIDGE
flag?
The Javadoc for Method.isBridge()
says it returns true if this method is a bridge method as defined by the Java Language Specification.
But I can't find any actual definition in the JLS.
This is not a "bridge method" under the normal definition of that term as I've understood it, which is one created to handle narrowing types due to generics and type erasure.
Perhaps there's really just some ambiguity here, in which case Method.isBridge()
needs a more precise definition... ?
$ javac -version
javac 11.0.12
$ java -version
openjdk version "11.0.12" 2021-07-20
OpenJDK Runtime Environment Homebrew (build 11.0.12+0)
OpenJDK 64-Bit Server VM Homebrew (build 11.0.12+0, mixed mode)
Copyright Notice:Content Author:「Archie」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71042938/why-is-this-java-method-reported-as-a-bridge-method