动态代理

interface AService{
    void fly();
}
class AServiceImpl implements AService{
    @Override
    public void fly(){
        System.out.println("fly......");
    }
}
// jdk自带动态代理实现方式
class JDKHandler implements InvocationHandler {
    private Object obj;
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // proxy是生成的代理类对象 
        System.out.println("开始时间:"+System.currentTimeMillis());
        Object ret = method.invoke(obj,args);
        System.out.println("结束时间:"+System.currentTimeMillis());
        return ret; // 返回原方法的结果
    }
    public JDKHandler(Object obj){
        this.obj = obj;
    }
}
// cglib方式
class CglibHandler implements MethodInterceptor {
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        // proxy 是代理的方法对象
        System.out.println("开始时间:"+System.currentTimeMillis());
        Object ret = proxy.invokeSuper(obj,args); // 注意此处是invokSuper
        System.out.println("结束时间:"+System.currentTimeMillis());
        return ret
    }
}
public class Main {
    public static void main(String[] args) {
        AService service = new AServiceImpl();
        AService proxy = (AService) Proxy.newProxyInstance(
            AService.class.getClassLoader(),
            service.getClass().getInterfaces(),
            // 此处是子类实现的接口,根据子类获取,不能根据接口类获取
            // Aservice.class.getInterfaces() 错误
            // AserviceImpl.class.getInterfaces()
            new JDKHandler(service));
        proxy.fly();
    }
}
public class Main {
    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(AServiceImpl.class);// 此处是子类,不是接口,要注意
        enhancer.setCallback(new CglibHandler());
        ((AServiceImpl) enhancer.create()).fly();
    }
}
posted @ 2021-03-03 19:52  下雨天,真好  阅读(36)  评论(0编辑  收藏  举报