java interview -java dynamic proxy and proxy cglib

  Proxy mode is to provide additional or different operations, and used instead of the actual object inserted objects, these operations relate to the actual communication with the object, such that the agent typically acts as middleman

A, java dynamic proxy

  java dynamic proxy agent can dynamically create and dynamically handle calls to the proxy approach. In the dynamic proxy all calls made will be redirected to the processor on a single call.

1, dynamic proxies are five steps

(1) write interfaces and implementation classes
public interface UserDao {
    void addUser(String var1);
}

public class UserDaoImpl implements UserDao{
    @Override
    public void addUser(String userName) {
        System.out.println("添加用户"+userName);
    }
}
(2) by implementing an interface to customize your own InvocationHandler InvocationHandler (mainly written invoke method)
public class LogHandler implements InvocationHandler {
    private Object target;
    public LogHandler(Object target){
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("开始记录日志");
        method.invoke(target,args);
        System.out.println("结束记录日志");
        return null;
    }
}
(3) create a proxy object using the method and implement methods Proxy.newProxyInstance
        UserDao userDao = new UserDaoImpl();
        //构造函数中传入实际对象
        LogHandler logHandler = new LogHandler(userDao);
        UserDao userDAOProxy = (UserDao) Proxy.newProxyInstance(userDao.getClass().getClassLoader(),
                userDao.getClass().getInterfaces(),logHandler);
        userDAOProxy.addUser("aaa");

2, the principle of java dynamic proxy resolution

  core java dynamic proxy is Proxy.newProxyInstance (ClassLoader loader, Class <? > [] interfaces, InvocationHandler h). For generating a proxy object.
  ClassLoader loader: generating a proxy object for indicating which class loader.
  Class [] interfaces <?>: Used to specify which object proxy object is generated (proxy class and target class needs to implement the same interface)
  InvocationHandler H: The last method calls to our self-definition.

3, newProxyInstance process of a method of generating a proxy object

  (1) obtaining a class bytecode dynamic proxy class through the content Proxy.getProxyClass (ProxyGenerator.generateProxyClass (proxyName, interfaces) ).
  (2) passing through the loading bytecode class loader into the virtual machine, then the proxy class constructor is obtained by reflection (method signature getConstructor (InvocationHandler.class)), to generate the proxy class object

Guess you like

Origin www.cnblogs.com/ssl-bl/p/11043243.html