public class Object {
public void doSomething() {
// 被代理对象的方法
System.out.Println("被静态代理的对象");
}
}
public class StaticProxyObject {
private Object object;
public StaticProxyObject(Object object) {
this.object = object;
}
public void doSomething() {
// 代理方法
System.out.Println("执行被代理方法前执行逻辑");
object.doSomething();
System.out.Println("执行后代理方法前执行逻辑");
}
}
public class Deer implements DeerI{
@Override
public void saySomething() {
System.out.println("Deer Class say hello");
}
@Override
public void doSomething() {
System.out.println("Deer Class is cooking");
}
}
interface DeerI {
void saySomething();
void doSomething();
}
class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public ProxyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("method name is:" + method.getName());
return method.invoke(target, args);
}
}
class DeerMain {
public static void main(String[] args) {
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
DeerI deer = new Deer();
Class<?>[] interfaces = deer.getClass().getInterfaces();
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler(deer);
Object object = Proxy.newProxyInstance(deer.getClass().getClassLoader(), deer.getClass().getInterfaces(), proxyInvocationHandler);
DeerI proxyDeer = (DeerI)Proxy.newProxyInstance(deer.getClass().getClassLoader(), deer.getClass().getInterfaces(), proxyInvocationHandler);
System.out.println("代理对象是:" + proxyDeer);
proxyDeer.saySomething();
}
}
invoke的参数Method表明JDK动态代理是基于反射机制实现的,在invoke方法中通过反射可以调用被代理对象的方法,同时可以在调用之前横向插入逻辑扩展功能。
JDK动态代理和Cglib动态代理的区别:
JDK是基于代理对象的接口实现的,Cglib是基于继承子类实现的
代理没有实现类的接口时,扩展的功能被加到了invoke中,invoke的返回值是invoke的返回值。而代理有接口的实现类时,invoke的返回值是被代理对象方法的返回值。
原文:https://www.cnblogs.com/deer-hang/p/14772767.html