了解什么是動(dòng)態(tài)代理模式,可參考Java設(shè)計(jì)模式之代理模式
簡(jiǎn)介
- JDK動(dòng)態(tài)代理是java.lang.reflect.*包所提供的方式锦溪,它所代理的真實(shí)對(duì)象必須實(shí)現(xiàn)一個(gè)接口樊零,依據(jù)該接口才能生成真實(shí)對(duì)象的代理酣难。
- 在JDK動(dòng)態(tài)代理中拖叙,想要實(shí)現(xiàn)代理邏輯類,必須實(shí)現(xiàn)java.lang.reflect.InvocationHandler接口蜡歹,它里面定義了一個(gè)invoke方法來(lái)實(shí)現(xiàn)具體的代理邏輯屋厘。
- 下面示例的具體代碼可到jdk動(dòng)態(tài)代理中下載。
示例
【真實(shí)對(duì)象類及其接口】
//接口
public interface HelloWorld {
void sayHelloWorld();
}
//實(shí)現(xiàn)對(duì)象
public class HelloWorldImpl implements HelloWorld {
@Override
public void sayHelloWorld() {
System.out.println("hello world!");
}
}
【動(dòng)態(tài)代理綁定和代理邏輯實(shí)現(xiàn)】
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JdkProxyExample implements InvocationHandler {
//真實(shí)對(duì)象
private Object target = null;
/**
* 建立代理對(duì)象和真實(shí)對(duì)象的代理關(guān)系月而,并且返回代理對(duì)象
* @param target 真實(shí)對(duì)象
* @return 代理對(duì)象
*/
public Object bind(Object target){
this.target = target;
/*
* newProxyInstance參數(shù)
* 1汗洒、類加載器
* 2、將生成的代理對(duì)象掛到哪些接口下
* 3父款、實(shí)現(xiàn)了代理邏輯的代理類(實(shí)現(xiàn)InvocationHandler接口)
* */
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
/**
* @param proxy 代理對(duì)象
* @param method 當(dāng)前調(diào)度方法
* @param args 當(dāng)前方法參數(shù)
* @return 代理結(jié)果返回
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("進(jìn)入代理邏輯方法");
System.out.println("在調(diào)度真實(shí)對(duì)象之前的服務(wù)");
Object obj = method.invoke(target, args);
System.out.println("在調(diào)度真實(shí)對(duì)象之后的服務(wù)");
return obj;
}
}
【測(cè)試】
public class TestJdkProxy {
public static void main(String[] args) {
JdkProxyExample jdk = new JdkProxyExample();
//綁定關(guān)系
HelloWorld proxy = (HelloWorld) jdk.bind(new HelloWorldImpl());
proxy.sayHelloWorld();
}
}
【測(cè)試結(jié)果】
測(cè)試結(jié)果