Dynamic proxy for JDK

A class that requires the target class to implement the business interface.

Principle: The client class calls the proxy method, the proxy class method calls the delegate class, the delegate class calls the invoke method, the invoke calls the target method,

invoke (

        proxy object;

        Target method:

        target method parameter);

The name of the proxy object consists of three parts: $+proxy+number;

The target class object is created in the delegate class, which is not common, and is usually created in the delegate class. Injected by the constructor.


By watching the code I found:

       1. The delegate class calls Proxy.newProxyInstnce; 2. Then P.newProxy calls the delegate class; 3. The delegate class calls the invoke method;

       4. The invoke method calls the target class method;


        Here is my practice code:

public interface service {
//Business interface
 String doSome(int a,String b);
 void doOther();
}

           public class serviceImple implements service { // target method @Override public String doSome(int a, String b) { System.out.println("execute business method doSome()"); return a + b; } // target method @ Override public void doOther() { System.out.println("Execute business method doOther()"); }











}

package entrusts;


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


import Service.service;
//The delegate class creates
public class ProxyEntrust implements InvocationHandler {
private service target;
//The constructor injects
public ProxyEntrust(service target) {
super();
this.target = target;
}
//proxy: proxy object
//Method: target method
//args: target parameter
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//Execute the target method
Object result=method.invoke(target,args);
return result;
}

}

package client;


import java.lang.reflect.Proxy;


import Service.service;
import Service.serviceImple;
import entrusts.ProxyEntrust;


public class Client {
public static void main(String[] args) {
// Create target object
service target = new serviceImple();
// Create delegate object
ProxyEntrust ih = new ProxyEntrust(target);
// Create proxy object
service service = (service) Proxy.newProxyInstance(
target.getClass().getClassLoader(), // class of target class Loader 
target.getClass().getInterfaces(), // all interfaces implemented by target class
ih); // delegate object                     
// call delegate method of delegate object
String someResult = service.doSome(5, "month");
System.out.println("someResult = " + someResult);}}












Guess you like

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