Java proxy JDK dynamic proxy application files

  • 2020-04-01 01:08:11
  • OfStack

Java agent has JDK dynamic agent, cglib agent, here only mentioned JDK dynamic agent, JDK dynamic agent mainly USES Java reflection mechanism (both java.lang.reflect package)
Here's how it works (singers, managers) :
Establish a public interface, such as: Singer public interface Singer;
Implements an interface with a concrete class, such as jay Chou, who is a Singer so implements the class Singer, class MySinger implements Singer
To create the proxy class, which is the broker in this case, he needs to implement the InvocationHandler class and override the invoke method
This way, when there is something to find jay Chou (specific class), you must first go to the broker (agent class) to deal with the agent in the decision to meet with you (the method is to be implemented)
1. Singer interface
 
public interface Singer { 

public abstract void sing(); 

public abstract String s(); 
} 

2. Specific singers
 
public class MySinger implements Singer { 
public void sing() { 
// TODO Auto-generated method stub 
System.err.println(" Sing... "); 
} 
} 

3. Agent (broker)
 
public class agent implements InvocationHandler{ 
public Object target; 

//The binding
public Object bind(Object target){ 
this.target=target; 
//You must put the Proxy back
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); 
} 

//again
public Object invoke(Object proxy, Method method, Object[] args) 
throws Throwable { 
Object o =null; 
System.out.println(" Start the transaction "); 
System.out.println(" Judge authority "); 

o = method.invoke(target, args);//Execution method

System.out.println(" End of the transaction "); 
return o; 
} 
} 

4, test (why to indirect port, the following you will find that the proxy returned is their interface class, which requires a proxy class, you can proxy multiple classes, as long as the class is the same as an interface is the implementation)
 
public class Test { 
public static void main(String[] args) { 
// 
agent a =new agent(); 
Singer s= (Singer) a.bind(new MySinger()); 
s.sing(); 
} 
} 

Related articles: