Proxy provides static methods for creating dynamic proxy classes and instances. Concise method:
Foo f = (foo) proxy.newproxyinstance (Foo.class.getClassLoader (),
New class[] {Foo.class},
handler);
Invocationhandler is an interface implemented by the invocation handler of the proxy instance.
Each code instance has an associated invocation handler. When a method is invoked on a proxy instance, the method call is encoded and assigned to the Invoke method of its calling handler.
A little unfamiliar with the dynamic proxy mechanism for Java, sort out the previous code. Package invocation;
/** *//**
* Define an interface, two methods
* @author jessica
*
*/
Public Interface Subject ... {
public void print (STRING STR);
public void print2 ();
}
Package invocation;
/** */ /**
* Define a class to implement the subject interface
* @author Jessica
*
*/
public class Realobject implements Subject ... {
Public Realobject () ... {
Super ();
}
public void print (String str) ... {
System.out.println ("Run into print");
}
public void Print2 () ... {
System.out.println ("Run into Print2");
}
}
Package invocation;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
/** */ /**
* Implement Invocationhandler interface, provide proxy for Realobject object (proxy Class)
* @author Jessica
*
*/
public class CallBack implements Invocationhandler ... {
Private Object obj;
Public CallBack (Object obj) ... {
This.obj = obj;
}
/** *//**
* Create dynamic proxies for objects
* @param obj needs to create an object for the agent
* @return return Dynamic proxy object
*/
public static object factory (Object obj) ... {
Class cls = Obj.getclass ();
Return Proxy.newproxyinstance (Cls.getclassloader (),
Cls.getinterfaces (), New CallBack (obj));
}
/** *//**
* Handles the method call on the proxy instance and returns the result.
* This method is called on the calling handler when the method is invoked on the proxy instance associated with the method.
* @proxy-the proxy instance on which the method is invoked
* @method-method instance that corresponds to the interface methods invoked on the proxy instance
* @args-an array of objects containing parameter values for method calls on the incoming proxy instance
* @Throwable-Exceptions thrown from method calls on the proxy instance
*/