2018-11-19 反射

反射:运行时类信息

Person person = new Person("luoxn28", 23);

    Class clazz = person.getClass();

    Field[] fields = clazz.getDeclaredFields();

    for (Field field : fields) {

        String key = field.getName();

        PropertyDescriptor descriptor = new PropertyDescriptor(key, clazz);

        Method method = descriptor.getReadMethod();

        Object value = method.invoke(person);

        System.out.println(key + ":" + value);

    }

4、动态代理

public interface Interface {

    void doSomething();

    void somethingElse(String arg);

}

public class RealObject implements Interface {

    public void doSomething() {

      // System.out.println("doSomething.");

    }

    public void somethingElse(String arg) {

      // System.out.println("somethingElse " + arg);

    }

}

public class DynamicProxyHandler implements InvocationHandler {

    private Object proxyed;


    public DynamicProxyHandler(Object proxyed) {

        this.proxyed = proxyed;

    }


    @Override

    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        System.out.println("代理工作了.");

        return method.invoke(proxyed, args);

    }

}

RealObject real = new RealObject();

        Interface proxy = (Interface) Proxy.newProxyInstance(

                Interface.class.getClassLoader(), new Class[] {Interface.class},

                new DynamicProxyHandler(real));


        proxy.doSomething();

        proxy.somethingElse("luoxn28");

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,246评论 19 139
  • 深入理解Class对象 RRTI的概念以及Class对象作用 认识Class对象之前,先来了解一个概念,RTTI(...
    架构师springboot阅读 1,595评论 0 3
  • 多态 任何域的访问操作都将有编译器解析,如果某个方法是静态的,它的行为就不具有多态性 java默认对象的销毁顺序与...
    yueyue_projects阅读 998评论 0 1
  • 想要掌握就好像想要总结,想要总结旧相当于想要客观在外,这是为什么呢? 是融于生活会有什么危险,还是融于生活中,...
    bangjieuu阅读 69评论 0 0
  • 心底多情才兴奋,笔端无句不精神。 风光在目年年好,四季不同频写真。
    雪窗_武立之阅读 198评论 0 0