• Java反射的应用 --- 内省


    一、基础概念

    内省(Introspector) 是Java 语言对 JavaBean 类属性、事件的一种缺省处理方法。Java JDK中提供了一套 API 用来访问某个属性的 getter/setter 方法,这就是内省。


    BeanInfo:
    希望提供有关其 bean 的显式信息的 bean 实现者可以提供某个 BeanInfo 类,该类实现此 BeanInfo 接口并提供有关其 bean 的方法、属性、事件等显式信息。
    常用方法:
    getPropertyDescriptors():获得 beans PropertyDescriptor。
    返回:
    描述受此 bean 支持的可编辑属性的 PropertyDescriptor 数组。如果该信息应该通过自动分析获得,则可能返回 null。
    如果某个属性已建立索引,则结果数组中该属性的条目将属于 PropertyDescriptor 的 IndexedPropertyDescriptor 子类。
    getPropertyDescriptors 的客户端可以使用 "instanceof" 来检查给定 PropertyDescriptor 是否是一个 IndexedPropertyDescriptor。

    PropertyDescriptor
    描述 Java Bean 通过一对存储器方法导出的一个属性,继承FeatureDescriptor。

    FeatureDescriptor
    是 PropertyDescriptor、EventSetDescriptor 和 MethodDescriptor 等的公共基类。
    它支持一些可以设置和检索任意的内省描述符(introspection descriptor)的公共信息。
    此外,它还提供了一种扩展机制,从而任意属性/值对都可以与设计特性相关联。

    Introspector
    Introspector 类为通过工具学习有关受目标 Java bean 支持的属性、事件和方法的知识提供了一个标准方法。
    对于这三种信息,Introspector 将分别分析 bean 的类和超类,寻找显式和隐式信息,使用这些信息构建一个全面描述目标 bean 的 BeanInfo 对象。
    因为 Introspector 缓存 BeanInfo 类来获得更好的性能,所以如果在使用多个类加载器的应用程序中使用它,则需小心谨慎。通常,在破坏一个已用于 introspect 类的 ClassLoader 时,应使用 Introspector.flushCaches 和 Introspector.flushFromCaches 方法从缓存中清除所有内省的类。

    二、应用示例

        /**
         *  实体类转换成map形式
         */
        public static HashMap<String, Object> transBean2Map(Object obj) {
            if (obj == null) {
                return null;
            }
            HashMap<String, Object> map = new HashMap<String, Object>();
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor property : propertyDescriptors) {
                    String key = property.getName().substring(0, 1).toUpperCase() + property.getName().substring(1);
                    // 过滤class属性
                    if (!key.equals("class")) {
                        // 得到property对应的getter方法
                        Method getter = property.getReadMethod();
                        Object value = getter.invoke(obj);
                        if (null==value) {
                            continue;
                        }
                        map.put(key, value);
                    }
                }
            } catch (Exception e) {
            }
            return map;
        }


    参考文档:http://www.cnblogs.com/peida/archive/2013/06/03/3090842.html

  • 相关阅读:
    轻松构建微服务之分布式事物
    Java和操作系统交互细节
    网络内核之TCP是如何发送和接收消息的
    最全的微服务知识科普
    【译】TCP Implementation in Linux
    轻松构建微服务之分库分表
    OSX的一些基本知识
    Delphi中使用比较少的一些语法
    热烈祝贺我的博客开通
    Windows 服务快捷启动命令
  • 原文地址:https://www.cnblogs.com/archermeng/p/7537194.html
Copyright © 2020-2023  润新知