Java Learning Note 14--Dynamic agent
Invocationhandler interface
[Java]View Plaincopy
- Public Interface invocationhandler{
- Public object Invoke (Object Proxy,method method,object[] args)throws Throwable
- }
Parameter description:
Object proxy: The objects being proxied
Method: Methods to invoke
Object args[]: Parameters required for method invocation
proxy class
The proxy class is an action class that specifically completes the proxy, which can be used to dynamically generate an implementation class for one or more interfaces, which provides the following operations:
[Java]View Plaincopy
- Public static Object newproxyinstance (ClassLoader loader,
- Class<?>[] interfaces,
- Invocationhandler h)
- throws IllegalArgumentException
Parameter description:
ClassLoader Loader: Class loader
Class<?>[] Interfaces: Get all the interfaces
Invocationhandler h: Get subclass instance of Invocationhandler interface
Dynamic Agent:
[Java]View Plaincopy
- Package com.itmyhome;
- Import Java.lang.reflect.InvocationHandler;
- Import Java.lang.reflect.Method;
- Import Java.lang.reflect.Proxy;
- Interface ihello{ //define Interface
- public void SayHello ();
- }
- Class Helloimpl implements ihello{
- @Override
- public void SayHello () {
- //TODO auto-generated method stub
- System.out.println ("Hello Itmyhome");
- }
- }
- Class Myinvocationhandler implements invocationhandler{
- private Object obj; //Real theme class
- Public object bind (Object obj) {
- this.obj = obj;
- return Proxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), this );
- }
- @Override
- Public object Invoke (Object proxy, Method method, object[] args) throws Throwable {
- System.out.println ("***before***");
- Object temp = Method.invoke (obj, args);
- System.out.println ("***after***");
- return temp;
- }
- }
- Public class T {
- public static void Main (string[] args) throws exception{
- Ihello h = (Ihello)new Myinvocationhandler (). Bind (new Helloimpl ());
- H.sayhello ();
- }
- }
Java Learning Note 14--Dynamic Agent