Java proxies include jdk dynamic proxies and cglib proxies. Here we only talk about jdk dynamic proxies. jdk dynamic proxies mainly use java reflection mechanisms (both java. lang. reflect packages)
The principle is (examples of singers and agents ):
Create a public interface, such as the Singer public interface Singer;
Use a specific class to implement the interface. For example: Jay Chou, he is a Singer, so he implements the Singer class. class MySinger implements Singer
Create a proxy class, which is the broker. It needs to implement the InvocationHandler class and override the invoke method.
In this way, when looking for Jay Chou (specific class), you must first go to the broker (proxy class) to handle the problem, the agent is deciding whether to meet you (this method is required or not)
1. Artist Interface
Copy codeThe Code is as follows: public interface Singer {
Public abstract void sing ();
Public abstract String s ();
}
2. Specific singersCopy codeThe Code is as follows: public class MySinger implements Singer {
Public void sing (){
// TODO Auto-generated method stub
System. err. println ("singing .... ");
}
}
3. Proxy (broker)Copy codeThe Code is as follows: public class agent implements InvocationHandler {
Public Object target;
// Bind
Public Object bind (Object target ){
This.tar get = target;
// The Proxy must be put back.
Return Proxy. newProxyInstance (target. getClass (). getClassLoader (), target. getClass (). getInterfaces (), this );
}
// Repeat
Public Object invoke (Object proxy, Method method, Object [] args)
Throws Throwable {
Object o = null;
System. out. println ("START transaction ");
System. out. println ("determining Permissions ");
O = method. invoke (target, args); // execution method
System. out. println ("End transaction ");
Return o;
}
}
4. Test (Why can an interface be used? Next, you will find that the proxy Returns their interface classes. This requires a proxy class to proxy multiple classes, as long as the class is implemented by the same interface)Copy codeThe Code is as follows: public class Test {
Public static void main (String [] args ){
//
Agent a = new agent ();
Singer s = (Singer) a. bind (new MySinger ());
S. sing ();
}
}