Home >Java >javaTutorial >Example analysis of dynamic proxy in Java reflection mechanism

Example analysis of dynamic proxy in Java reflection mechanism

PHPz
PHPzforward
2023-05-13 08:37:051333browse

1. Proxy mode

The proxy mode is to provide a proxy for other objects to control access to this object. In fact, the proxy mode introduces a certain degree of indirection when accessing objects. This indirection can be attached to a variety of purposes.

Its characteristic is that the proxy class and the delegate class have the same interface. The proxy class is mainly responsible for preprocessing messages for the delegate class, filtering messages, forwarding messages to the delegate class, and processing messages afterwards. There is usually an association between a proxy class and a delegate class. An object of a proxy class is associated with an object of a delegate class. The object of the proxy class itself does not actually implement the service, but by calling the relevant methods of the object of the delegate class. Provide specific services.

2. Classification

Agent classes can be divided into two types according to the creation period, static proxy classes and dynamic proxy classes.

Static proxy class: Created by programmers or automatically generated by specific tools, and then compiled. Before the program is run, the .class file of the proxy class already exists.

Dynamic proxy class: dynamically created using the reflection mechanism when the program is running.

3. Examples of static proxy and dynamic proxy

Static proxy:

Business interface class:

package com.bjpowernode.pattern;   public interface UserManager {       public void addUser(String userId, String userName);            public void delUser(String userId);            public void modifyUser(String userId, String userName);            public String findUser(String userId);  }

Business interface implementation class :

package com.bjpowernode.pattern;   public class UserManagerImpl implements UserManager {       public void addUser(String userId, String userName) {          //System.out.println("start-->>addUser() userId-->>" + userId);          try {              System.out.println("UserManagerImpl.addUser() userId-->>" + userId);                            //System.out.println("success-->>addUser()");          }catch(Exception e) {              e.printStackTrace();              //System.out.println("error-->>addUser()");              throw new RuntimeException();          }         }       public void delUser(String userId) {          System.out.println("UserManagerImpl.delUser() userId-->>" + userId);      }       public String findUser(String userId) {          System.out.println("UserManagerImpl.findUser() userId-->>" + userId);          return "张三";      }       public void modifyUser(String userId, String userName) {          System.out.println("UserManagerImpl.modifyUser() userId-->>" + userId);      }   }

Business proxy class:

package com.bjpowernode.pattern;   public class UserManagerImplProxy implements UserManager {       private UserManager userManager;            public UserManagerImplProxy(UserManager userManager) {          this.userManager = userManager;      }            public void addUser(String userId, String userName) {          try {              System.out.println("start-->>addUser() userId-->>" + userId);              userManager.addUser(userId, userName);              System.out.println("success-->>addUser()");          }catch(Exception e) {              e.printStackTrace();              System.out.println("error-->>addUser()");          }         }       public void delUser(String userId) {       }       public String findUser(String userId) {          return null;      }       public void modifyUser(String userId, String userName) {       }  }

Client class:

package com.bjpowernode.pattern;   public class Client {       /**       * @param args       */     public static void main(String[] args) {          //UserManager userManager = new UserManagerImpl();          UserManager userManager = new UserManagerImplProxy(new UserManagerImpl());          userManager.addUser("0001", "张三");      }   }

Running result:

start-->>addUser() userId-->>0001 UserManagerImpl.addUser() userId-->>0001 success-->>addUser()

Dynamic proxy:

Business Interface class:

package com.bjpowernode.pattern;   public interface UserManager {             public String test(String userId);  }

Business interface implementation class:

package com.bjpowernode.pattern;   public class UserManagerImpl implements UserManager {       public String test(String userId) {          System.out.println("UserManagerImpl.findUser() userId-->>" + userId);          return "张三";      }   }

BusinessHandler class:

package com.bjpowernode.pattern;   import java.lang.reflect.InvocationHandler;  import java.lang.reflect.Method;  import java.lang.reflect.Proxy;   public class BusinessHandler implements InvocationHandler {            private Object targetObject;            public Object newProxyInstance(Object targetObject) {                    this.targetObject = targetObject;          return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),                                 targetObject.getClass().getInterfaces(), this);      }            public Object invoke(Object proxy, Method method, Object[] args)              throws Throwable {          System.out.println("start-->>" + method.getName());          for (int i=0; i<args.length; i++) {              System.out.println(args[i]);          }          Object ret = null;          try {              //调用目标方法              ret = method.invoke(targetObject, args);              System.out.println("success-->>" + method.getName());           }catch(Exception e) {              e.printStackTrace();              System.out.println("error-->>" + method.getName());              throw e;          }          return ret;      }   }

Client class:

package com.bjpowernode.pattern;   import java.lang.reflect.Field;    public class Client {       /**       * @param args       */     public static void main(String[] args) {                    BusinessHandler businessHandler = new BusinessHandler();          UserManager userManager = (UserManager)businessHandler.newProxyInstance(new UserManagerImpl());                                        //userManager.addUser("0001", "张三");          //userManager.delUser("0001");         // System.out.println(userManager.getClass().getName());                    String name = userManager.test("0001");      //String name = ((UserManagerImpl) logHandler.newProxyInstance(new UserManagerImpl())).test("0001");          System.out.println("Client.main() --- " + name);      }   }

Running result:

start-->>test  0001 UserManagerImpl.findUser() userId-->>0001 success-->>test  Client.main() --- 张三

The above is the detailed content of Example analysis of dynamic proxy in Java reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete