首页 > 编程语言 > 详细

JAVA 反射 动态代理

时间:2020-02-24 20:10:02      阅读:84      评论:0      收藏:0      [点我收藏+]

摘自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);
    }

 

JAVA 反射 动态代理

原文:https://www.cnblogs.com/superxuezhazha/p/12358437.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!