JAVA 反射 动态代理

摘自b站尚硅谷JAVA视频教程

 

 

interface HelloInterface {
    String sayHello();
}
class Hello implements HelloInterface{
    @Override
    public String sayHello() {
        System.out.println("Hello zhanghao!");
        return "Hello";
    }
}
class ProxyHandler implements InvocationHandler {
    private Object object;
    public ProxyHandler(Object object){
        this.object = object;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before invoke "  + method.getName());
        Object value = method.invoke(object, args);
        System.out.println("After invoke " + method.getName());
        return value;
    }
}
public class proxyTest {
    public static void main(String[] args) {
        HelloInterface hello = new Hello();

        InvocationHandler handler = new ProxyHandler(hello);

        HelloInterface proxyHello = (HelloInterface) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler);

        Object value = proxyHello.sayHello();
        System.out.println(value);
    }

 

posted @ 2020-02-24 19:48  超级学渣渣  阅读(157)  评论(0编辑  收藏  举报