JDK动态代理

public interface AnimalInterface {
    public void cry();
}
public class AnimalImpl implements AnimalInterface {

    public void cry() {
        // TODO Auto-generated method stub
        System.out.println("crying");
    }

}
public class MyProxy implements InvocationHandler {
    private Object proxied;

    private MyProxy(Object proxied) {
        this.proxied = proxied;
    }

    public static Object getProxy(Object proxied) {
        return Proxy.newProxyInstance(proxied.getClass().getClassLoader(),
                proxied.getClass().getInterfaces(), new MyProxy(proxied));
    }

    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        // TODO Auto-generated method stub
        Object ret;
        System.out.println("Before Method Invoke");
        ret = method.invoke(proxied, args);
        System.out.println("After Method Invoke");
        return ret;
    }

}
public class Test {
    public static void main(String[] args) {
        AnimalInterface animal = (AnimalInterface) MyProxy
                .getProxy(new AnimalImpl());
        animal.cry();
    }
}

 

posted @ 2015-01-24 11:55  小明湖畔  阅读(107)  评论(0编辑  收藏  举报