JDK
public class JdkProxy implements InvocationHandler {
private Object targetObject;
public Object newProxyInstance(Object targetObject){
this. targetObject = targetObject;
return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
targetObject.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method, Object[] args) {
Object result = null;
try{
System.out.println("通过JDK动态代理调用 "+method.getName() +", 打印日志 begin");
result = method.invoke(targetObject,args);
System.out.println("通过JDK动态代理调用 "+method.getName() +", 打印日志 end");
}catch (Exception e){
e.printStackTrace();
}
return result;
}
}
cgLIB
public class CglibProxy implements MethodInterceptor {
private Object targetObject;
public Object newProxyInstance(Object targetObject){
this.targetObject = targetObject;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.targetObject.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object result = null;
try{
System.out.println("通过CGLIB动态代理调用 "+method.getName() +", 打印日志 begin");
result = methodProxy.invokeSuper(o,args);
System.out.println("通过CGLIB动态代理调用 "+method.getName() +", 打印日志 begin");
}catch (Exception e){
e.printStackTrace();
}
return result;
}
}