java dyn proxy

package dyn;

public interface RealService {
    
    void buy();

}

===================
package dyn;

public class RealServiceImpl implements RealService {

    @Override
    public void buy() {
        //do real service ,such as crud
        System.out.println("buy big hourse... ....");
    }

}
===================

package dyn;

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


public class MyInvocationHandler implements InvocationHandler {
    //realObject
    private RealService target;


    public MyInvocationHandler(RealService target) {
        super();
        this.target = target;
    }

    @Override
    public Object invoke(Object arg0, Method method, Object[] obj)
            throws Throwable {
        System.out.println("make big money... ...");
        Object o = method.invoke(target,obj);
        System.out.println("kiss QQ");
        return o;
        
    }

    public Object getRealServiceProxyObj() {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this);
    }

}
===============================

package dyn;

public class TestDynProxy {

    public static void main(String[] args) {
        // reql obj
        RealService real = new RealServiceImpl();
        // trans  中间商
        MyInvocationHandler invocationHandler = new MyInvocationHandler(real);
        // proxy obj
        RealService realServiceProxyObj = (RealService)invocationHandler.getRealServiceProxyObj();
        
        realServiceProxyObj.buy();

    }
}

 

posted @ 2016-01-31 14:34  Alamps  阅读(242)  评论(0编辑  收藏  举报