1.HelloWorld

package reflect.proxy;

public interface HelloWorld {
    void print();
}

2.HelloWorldImpl

package reflect.proxy;

public class HelloWorldImpl implements HelloWorld{

    @Override
    public void print() {
        // TODO Auto-generated method stub
        System.out.println("hello world!");
    }
    
}

3.HelloWorldInvocationHandle

package reflect.proxy;

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

public class HelloWorldInvocationHandle implements InvocationHandler{
    private HelloWorld helloWorld;
    public HelloWorldInvocationHandle(HelloWorld helloWorld) {
        this.helloWorld = helloWorld;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        // TODO Auto-generated method stub
        System.out.println("动态代理-begin");
        Object result = method.invoke(helloWorld, args);
        System.out.println("动态代理-end");
        return result;
    }

}

4.HelloWorldProxyFactory

package reflect.proxy;

import java.lang.reflect.Proxy;

public class HelloWorldProxyFactory {
    public static HelloWorld getProxy(HelloWorld helloWorld) {
        HelloWorldInvocationHandle handle = new HelloWorldInvocationHandle(helloWorld);
        Object obj = Proxy.newProxyInstance(helloWorld.getClass().getClassLoader(), new Class[]{HelloWorld.class}, handle);
        return (HelloWorld)obj;
    }
    
    public static void main(String[] args) {
        HelloWorld helloWorld = new HelloWorldImpl();
        HelloWorld proxy = HelloWorldProxyFactory.getProxy(helloWorld);
        System.out.println(proxy.getClass().getName());
        proxy.print();
    }
}

 

posted on 2013-08-28 15:35  爱生活的夜  阅读(138)  评论(0编辑  收藏  举报