jdk实现动态代理
package proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class StarProxy implements InvocationHandler{
// 目标类,也就是被代理对象
private Object target;
public void setTarget(Object target) {
this.target = target; }
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 这里可以做增强 System.out.println("收钱");
Object result = method.invoke(target, args);
return result; } // 生成代理类
public Object CreatProxyedObj() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this); }
}
测试
Star ldh = new LiuDeHua();
StarProxy proxy = new StarProxy();
proxy.setTarget(ldh);
Object obj = proxy.CreatProxyedObj();
Star star = (Star)obj;
cglib
package proxy; import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CglibProxy implements MethodInterceptor{ // 根据一个类型产生代理类,此方法不要求一定放在MethodInterceptor中
public Object CreatProxyedObj(Class<?> clazz) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create(); }
@Override public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable { // 这里增强 System.out.println("收钱");
return arg3.invokeSuper(arg0, arg2); } }