The bridging method is a method that is automatically generated by the compiler after JDK 1.5 introduces generics, in order to make the bytecode generated by the Java generic method compatible with the bytecode before the 1.5 version. We can use the Method.isbridge () method to determine whether a method is a bridging method.
Assume that the interface
Public Interface Superclass<t> { void method (T t);}
One of its implementation classes
Public class Implements Superclass<string> { @Override publicvoid method (String s) {
System.out.println (s);
}
Because generics are introduced in 1.5, generics (generic erase) are removed at compile-time for forward compatibility. Then the parameters of method methods in the superclass interface can only be object in the virtual machine.
It should look something like this:
Public Interface Superclass { void method (Object t);}
The AClass implements the superclass interface, but it implements the following methods:
Public void
There is no way to implement the Void method (Object t). What's going on, actually the virtual machine automatically implements a method.
The AClass is this way in the virtual machine:
Public class Implements Superclass { publicvoid method (String s) { System.out.println (s); } Public void method (Object s) { this. Method ((String) s); }}
This void method (Object s) is the bridging approach.
We use this command to view
Javap-p AClass. class
Shown below:
Compiled from ' Aclass.java 'publicclassimplements superclass<java.lang.string> { public aclass (); Public void method (java.lang.String); Public void method (Java.lang.Object);}
We use reflection to write a test to see how the results
Public Static void throws Exception { new aclass (); = AClass. class. GetMethod ("Method", String. Class); " Xxxxxxxxxxxxxxxxxx "); System.out.println (M.isbridge ()); = AClass. class. GetMethod ("Method", Object. ) Class); " ##################"); System.out.println (M.isbridge ()); }
The test results are as follows
xxxxxxxxxxxxxxxxxx false ################## true
Method.isbridge () Bridging method in Java reflection