Reflective dynamic proxy

This section is the last chapter of reflection, dynamic proxy. If you are familiar with Android development and have used the Retrofit framework, you should know that the core of the Retrofit framework implementation is dynamic proxy.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//Interface: core theme
 interface Subject{
     void action();
}

//The proxied class (the real class to be executed)
 class RealSubject implements Subject{

    @Override
public void action() {    
        System.out.println ( "I am the proxy class" ) ;
    }
}

//The class that implements dynamic proxy---(proxy class)
 class MyInvocationHandler implements InvocationHandler{
    Object obj ; //Declaration of the proxy class object that implements the Subject interface
 public Object bind(Object obj){
         //Assign
 this to the proxy class object . obj = obj;
         //Return a proxy class object
 return Proxy. newProxyInstance (obj .getClass().getClassLoader(),obj.getClass().getInterfaces(), this );                    
    }

    //Call @Override
 when the overridden method is invoked through the proxy class object
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
         return method.invoke( obj ,args);        
    }
}


/**
 * Dynamic proxy mode
 */
 public class DynamicProxy {

    public static void main(String[] args){
         //Instantiate "proxy class"
         RealSubject realSubject = new RealSubject();
         //Instantiate "proxy class"
         MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
         //Proxy class object "Bind" the proxied class object
         Subject subject = (Subject) myInvocationHandler.bind(realSubject);
         //call the method
         subject.action();
    }

}
 
 

Well, the introduction to the knowledge about the reflection series ends in this paragraph.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325584324&siteId=291194637