1. Create a new interface Userdao
public interface userdao{
public void Save (User u);
}
2. Implement the interface
public class Userdaoimpl implements userdao{
public void Save (User u) {
System.out.println (u+ "save!");
}
}
3. Create a new business logic object to add a log when calling the method of the Proxied object
public class Logintercepter implements invocationhander{
Private object target;//The target object, also called the Proxied object
Public Object Gettarget () {
return target;
}
public object Settarget (object target) {
This.target =target;
}
public void Beforemethod (Method m) {
System.out.println (M.getname () + "Start,log remeber! ");
}
public object Invoke (Object Proxy,method m,object[] args) {
Beforemethod (m);
M.invoke (Target,args);
return null;
}
}
public void Testproxy () {//test method
Userdao userdao=new Userdaoimpl ();
Logintercepter li=new Logintercepter ();
Li.settarget (Userdao);//Set the object to be proxied
Userdao userdaoproxy = (Userdao) proxy.newproxyinstance (Userdao.getclass (). getClassLoader (), UserDAO.getClass (). Getinterfaces (), Li);
Userdaoproxy is a proxy object for Userdao
Userdaoproxy.save (New User ());
}
Native Java implements several key points of dynamic agent
1. The proxy object must be an interface form
2, the specific business logic object must implement the Invocationhander interface, and rewrite the Invoke method, while the proxy object can be set in
3. When you create a proxy object, Proxy.newproxyinstance (... ) method, note the incoming parameter
Implementation of the Java proxy