实现JDK动态代理和cglib动态代理

1,JDK

public class JDKProxy {
private Object target;


public JDKProxy(Object target) {
this.target = target;
}


public Object getInstance() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {


@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
System.out.println("你是谁");
Object result = method.invoke(target, args);
System.out.println("我是代理");
return result;
}
});
}


}


2cglib

public class CGProxy implements MethodInterceptor {

private Class c;

public CGProxy(Class c){
this.c = c;
}

public Object getinstance(){
Enhancer en = new Enhancer();
en.setSuperclass(c);
en.setCallback(this);
return en.create();
}


@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
System.out.println("CGlib代理!");
Object result = arg3.invokeSuper(arg0, arg2);
return result;
}
}

你可能感兴趣的:(设计模式)