美文网首页
java动态代理

java动态代理

作者: sngths | 来源:发表于2017-01-13 09:25 被阅读4次
    public class DynamicProxyTest {
    
        @Test
        public void test(){
            MyProxy proxy = new MyProxy();
            Subject subject = proxy.getNewInstance(Subject.class);
            System.out.println(subject.doSomething("a"));
        }
    
        private interface Subject{
            String doSomething(String str);
        }
    
        private class SubjectImp implements Subject{
    
            @Override
            public String doSomething(String str) {
                return str;
            }
        }
    
        private class InvocationHandlerImp implements InvocationHandler{
            private Object target;
    
            public InvocationHandlerImp(){
    
            }
    
            public InvocationHandlerImp(Object o){
                this.target = o;
            }
    
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (this.target != null){
                    return method.invoke(this.target, args);
                }else {
                    return args[0];
                }
    
            }
        }
    
        private class MyProxy{
    
            @SuppressWarnings("unchecked")
            public <T> T getNewInstance(Class<T> type){
                type.getInterfaces();//类和接口对象 返回结果不同
                return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new InvocationHandlerImp());
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:java动态代理

          本文链接:https://www.haomeiwen.com/subject/wcojbttx.html