Object java.lang.reflect.Proxy.newProxyInstance (ClassLoader loader, class<?>[] Interfaces,invocationhandler H ) throwsillegalargumentexception
Returns an instance of a proxy class for the specified interfaces which dispatches method invocations to the specified Cation handler
This means that the method returns a proxy class for the specified interface, which dispatches the method call to the specified invocation handle, the so-called invocation handler is the proxy.
It is clear that the classes in the JDK to be dynamically represented need to implement an interface.
public class Robotproxy implements Invocationhandler {
private Object target;
@Override Public
object Invoke (Object proxy, Method method, object[] args)
throws Throwable {
SYSTEM.OUT.PRINTLN ("Robot proxy access");
Object result = Method.invoke (target, args);
SYSTEM.OUT.PRINTLN ("Robot proxy Leave");
return result;
}
public object getinstance (object target) {
this.target = target;
Return Proxy.newproxyinstance (Target.getclass (). getClassLoader (),
Target.getclass (). Getinterfaces (), this);
}
Using agents
Robot Robot = new Robot ();
Robotproxy rproxy = new Robotproxy ();
Language IRobot = (Language) rproxy.getinstance (robot);
Irobot.spell ("Hello World, I name is a intelegent robot!");
This proxy returns the interface type
Robot IRobot = (Robot) rproxy.getinstance (Robot);
Change to the above code will be an error
Exception in thread "main" Java.lang.ClassCastException: $Proxy 0 cannot is cast to Robot
At Robottest.main (robottest.java:13)
Cglib is a dynamic proxy that is implemented by generating subclasses of classes, allowing the interface to be represented without implementation.
public class Robotcglibproxy implements Methodinterceptor {
private Object target;
public object getinstance (object target) {
this.target = target;
Enhancer enhancer = new enhancer ();
Enhancer.setsuperclass (Target.getclass ());
Enhancer.setcallback (this);
return Enhancer.create ();
}
@Override public
Object intercept (Object obj, Method method, object[] args,
methodproxy proxy) throws Throwable {
System.out.println ("Robot cglib proxy Access");
Object result = Proxy.invoke (target, args);
System.out.println ("Robot cglib proxy Leave");
return result;
}
To test the interface, I removed it.
public class Robot {public
void spell (String words) {
System.out.println (words);
}
Public String Getrobotname () {return
' Timi ';
}
}
Robot Robot = new Robot ();
Robotcglibproxy rcproxy = new Robotcglibproxy ();
Robot Icrobot = (Robot) rcproxy.getinstance (Robot);
Icrobot.spell ("Hello World, I name is a intelegent robot!");
System.out.println ("Robot name is:" +icrobot.getrobotname ());