动态代理接口实现类

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.test.crm.service.MarketService;

public class TransactionInvocationHandler2 implements InvocationHandler {
    public static void main(String[] args) {
        /**
         * 使用方式:代理类接口   接口变量 = new TransactionInvocationHandler2(new 该接口实现类).getProxy();
         * eg:xxxService 接口变量 = (xxxService) new TransactionInvocationHandler2(new xxxServiceImpl()).getProxy();
         */
        MarketService ms = (MarketService) new TransactionInvocationHandler2(new MarketServiceImpl()).getProxy();
        /**
         * MarketServiceImpl add()方法 -->System.out.print("1");
         */
        ms.add();//1
    }
    private Object target;
    
    public TransactionInvocationHandler2(Object target) {
        this.target = target;
    }

    public Object getProxy(){
        return  Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        /*
         * 这里添加额外的业务
         */
        
        Object obj = method.invoke(target, args);
        
        return obj;
    }
}

猜你喜欢

转载自blog.csdn.net/tanganq/article/details/81268536
今日推荐