靜態(tài)代理
創(chuàng)建一個(gè)接口,然后創(chuàng)建被代理的類(lèi)實(shí)現(xiàn)該接口并且實(shí)現(xiàn)該接口中的抽象方法。之后再創(chuàng)建一個(gè)代理類(lèi),同時(shí)使其也實(shí)現(xiàn)這個(gè)接口。在代理類(lèi)中持有一個(gè)被代理對(duì)象的引用,而后在代理類(lèi)方法中調(diào)用該對(duì)象的方法。
接口:
public interface HelloInterface {
void sayHello();
}
被代理的類(lèi):
public class Hello implements HelloInterface{
@Override
public void sayHello() {
System.out.println("ZHANGSAN");
}
}
代理類(lèi):
public class HelloProxy implements HelloInterface{
private HelloInterface helloInterface = new Hello();
@Override
public void sayHello() {
System.out.println("Before invoke sayHello" );
helloInterface.sayHello();
System.out.println("After invoke sayHello");
}
}
代理類(lèi)調(diào)用:
package cn.itcast.test;
public class test {
public static void main(String[] args){
HelloProxy helloProxy = new HelloProxy();
helloProxy.sayHello();
}
}
//輸出:
before invoke sayhello
ZHANGSAN
after invoke sayhello
動(dòng)態(tài)代理
利用反射機(jī)制在運(yùn)行時(shí)創(chuàng)建代理類(lèi)。
接口、被代理類(lèi)不變,我們構(gòu)建一個(gè)handler類(lèi)來(lái)實(shí)現(xiàn) InvocationHandler接口。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyHandler implements InvocationHandler{
private Object obj;
public ProxyHandler(Object object) {
super();
this.obj = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before invoke" + method.getName());
method.invoke(obj);
System.out.println("After invoke" + method.getName());
return null;
}
}
執(zhí)行動(dòng)態(tài)代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class test1 {
public static void main(String[] args) {
System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
Hello hello = new agentHelloIterface();
InvocationHandler handler = new ProxyHandler(hello);
Hello proxyHello = (Hello) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler);
proxyHello.sayHello();
}
}
//輸出
Before invokesayHello
ZHANGSAN
After invokesayHello