JDK的动态代理

要求目标类必须实现业务接口的类 。

原理:客户类调用代理方法,代理类 方法调用委托类,委托类调用invoke方法,invoke调用 目标方法,

invoke (

        代理对象;

        目标方法:

        目标方法参数);

代理对象的名称有三部分构成:$+proxy+数字;

目标类对象在委托类中创建,这种情况不常见,一般都是在委托类中创建。由构造器注入的。


通过观看 代码我发现:

       1. 委托类调用Proxy.newProxyInstnce;    2.然后P.newProxy调用委托类;  3.委托类调用invoke方法;

       4.invoke方法调用目标类方法;


        以下是我实践代码:

public interface service {
//业务接口
 String doSome(int a,String b);
 void doOther();
}

           public class serviceImple implements service {
// 目标方法
@Override
public String doSome(int a, String b) {
System.out.println("执行业务方法doSome()");
return a + b;
}
// 目标方法
@Override
public void doOther() {
System.out.println("执行业务方法doOther()");
}

}

package entrusts;


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


import Service.service;
//委托类创建
public class ProxyEntrust implements InvocationHandler {
private service target;
//构造方法注入
public ProxyEntrust(service target) {
super();
this.target = target;
}
//proxy:代理对象
//Method:目标方法
//args:目标参数
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//执行目标方法
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) {
// 创建目标对象
service target = new serviceImple();
// 创建委托对象
ProxyEntrust ih = new ProxyEntrust(target);
// 创建代理对象
service service = (service) Proxy.newProxyInstance(
target.getClass().getClassLoader(),  // 目标类的类加载器 
target.getClass().getInterfaces(),   // 目标类所实现的所有接口
ih);                                 // 委托对象                     
// 调用代理对象的代理方法
String someResult = service.doSome(5, "月份");
System.out.println("someResult = " + someResult);

}
}









猜你喜欢

转载自blog.csdn.net/qq_40406929/article/details/79801803
今日推荐