java – method bridge

java reflection could get all methods of a class.

isBridge() could check whether method is bridged or not.

when we override parent class general type method in child class, method will become bridged.

here is example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package org.spring.main;
 
import java.lang.reflect.Method;
 
import org.springframework.core.BridgeMethodResolver;
 
public class BridgeMethodResolverEntry {
 
	public class Node<T> {
 
	    public T data;
 
	    public Node(T data) { this.data = data; }
 
	    public void setData(T data) {
	        System.out.println("Node.setData");
	        this.data = data;
	    }
	}
 
	public class MyNode extends Node<Integer> {
 
	    public MyNode(Integer data) { super(data); }
 
	    @Override
	    public void setData(Integer data) {
	        System.out.println("MyNode.setData");
	        super.setData(data);
	    }
	}
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BridgeMethodResolverEntry x = new BridgeMethodResolverEntry();
		MyNode resolver = x.new MyNode(5);
		Method[] declaredMethods = resolver.getClass().getDeclaredMethods();
 
		for (int i = 0; i < declaredMethods.length; i++) {
		            Method declaredMethod = declaredMethods[i];
		            String methodName = declaredMethod.getName();
		            Class<?> returnType = declaredMethod.getReturnType();
		            Class<?> declaringClass = declaredMethod.getDeclaringClass();
		            boolean bridge = declaredMethod.isBridge();
		            System.out.print((i+1) + " method name is" + methodName + ", return type is " + returnType + "  ");
		            System.out.print(bridge ? " is Bridge Method" : " is not Bridge Method");
		            System.out.println("  it is declared at "+declaringClass.getSimpleName()+"");            
		}                        
 
	}
 
}