First: Define an interface// can only be an interface
Cases:
Package Dongtai;
Public interface Dongtai {
public void Show ();
}
Next: Define a proxy class to implement this interface
Cases:
Package Dongtai;
public class Bei implements dongtai{
@Override
public void Show () {
TODO auto-generated Method Stub
SYSTEM.OUT.PRINTLN ("proxy class");
}
}
Again: Define a proxy class, implement the Invocationhandler interface, override the Invoke () method of the interface
Cases:
Package Dongtai;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import org.omg.CORBA.SystemException;
Import Org.omg.CORBA.portable.InputStream;
Import Org.omg.CORBA.portable.InvokeHandler;
Import Org.omg.CORBA.portable.OutputStream;
Import Org.omg.CORBA.portable.ResponseHandler;
public class Bai implements invocationhandler{
Private Object o; //Here is an object type, representing acceptable any type
Public Bai (Object o) {
Super ();
THIS.O = O;
}
@Override
public object Invoke (Object object, method method, object[] arg) throws Throwable {
System.out.println ("Pre-call");
Method.invoke (o, arg); //method is a method of dynamic (created in operation) class, ARG is the parameter of the method
System.out.println ("after call");
return null;
}
}
At last:
Cases:
Package Dongtai;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Proxy;
public class Test {
public static void Main (string[] args) {
Bei B=new bei ();//Create a proxy class object
Invocationhandler In=new Bai (b);
Invokes the handler, creates the proxy class object, and passes the proxy class object to its constructor, because it implements the Invocationhandler and uses polymorphism to Invocationhandler type
Class Classtype=in.getclass ();//Create in class
Dongtai daili= (Dongtai) proxy.newproxyinstance (//Implement a new proxy, switch to interface class
Classtype.getclassloader (), B.getclass (). Getinterfaces (), in);//Parameter meaning: 1. class loader 2. Interface 3 implemented by the agent. instance of dynamic class to Invocationhandler
Note: The above two lines of code 1.2.
Daili.show ();
}
}
Java Dynamic Agent Summary