Java proxies include jdk dynamic proxy and cglib proxy. Here we only talk about jdk dynamic proxy. JDK dynamic proxy mainly uses the java reflection mechanism (that is, the java.lang.reflect package)
The principle is (singers and managers are examples):
Establish a public interface, such as: 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 an agent class, which is the broker here. He needs to implement the InvocationHandler class and rewrite the invoke method so that when something happens and you want to find Jay Chou (concrete class), you must first go to the broker (agent class) to handle it. The agent is deciding whether to meet with you (whether to execute this method)
1. Singer interface
public abstract void sing();
public abstract String s();
}
//Bind
public Object bind(Object target){
this.target=target;
//Proxy must be put 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 transaction");
System.out.println("Judge permissions");
o = method.invoke(target, args);//execution method
System.out.println("End transaction");
return o;
}
}