码迷,mamicode.com
首页 > 其他好文 > 详细

Dynamic proxy

时间:2016-01-08 18:43:10      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

 

package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by 10159705 on 16-1-8.
 */
public class DynamicProxyTest {
    interface IHello {
        void sayHello();
    }

    static class Hello implements IHello {

        @Override
        public void sayHello() {
            System.out.println("hello world");
        }
    }

    static class DynamicProxy implements InvocationHandler {

        Object originalObj;

        Object bind(Object originalObj) {
            this.originalObj = originalObj;
            return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(), originalObj.getClass().getInterfaces(), this);
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("add by Dynamic proxy:welcome.");
            return method.invoke(originalObj, args);
        }
    }

    public static void main(String[] args) {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

        //这个地方生成的hello实例,这个hello已经不是定义好的hello了
        IHello hello = (IHello) new DynamicProxy().bind(new Hello());
        hello.sayHello();
    }


}

 

Dynamic proxy

标签:

原文地址:http://www.cnblogs.com/softidea/p/5113996.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!