java jdk可以实现动态代理,CGLB也可以实现动态代理,今天写一个基于jdk的动态代理。
jdk实现动态代理,被代理的类必须实现一个接口,CGLB则不用。
public interface SayHelloInterface {
void sayHello();
}
public class SayHelloService implements SayHelloInterface {
public void sayHello() {
System.out.println("hello");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class SayHelloProxy implements InvocationHandler {
private Object target;
public Object bind(Object target){
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(target, args);
}
}
public class SayHelloProxyTest {
public static void main(String[] args) {
SayHelloProxy sayHelloProxy = new SayHelloProxy();
SayHelloInterface sayHelloService = (SayHelloInterface) sayHelloProxy.bind(new SayHelloService());
sayHelloService.sayHello();
}
}