java基础知识梳理&代理模式之动态代理

代理接口对象

public interface Service {

    Result toTestOne(String toTestOne);

    Result toTestTwo(String toTestTwo);

    interface Result {
  
        void printLog();

        void savaLog();
    }
}

简单代理逻辑

    public  T create(final Class service) {

        return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class[]{service}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, final Object[] args) throws Throwable {

                return new Service.Result() {
                    @Override
                    public void printLog() {
                        System.out.println("printLog=====>" + args[0]);
                    }

                    @Override
                    public void savaLog() {
                        System.out.println("savaLog=====>" + args[0]);
                    }
                };
            }
        });
    }

验证测试

        Service service = create(Service.class);
        service.toTestOne("toTestOne").printLog();
        service.toTestTwo("toTestTwo").savaLog();

验证结果

printLog=====>toTestOne
savaLog=====>toTestTwo

 

你可能感兴趣的:(#,基础知识,JAVA,Proxy)