首页 > 其他 > 详细

自省(Introspector)

时间:2020-02-23 13:33:59      阅读:62      评论:0      收藏:0      [点我收藏+]


无意间看到了内省,与反射相关联,所以写了一点操作


1. 内省


反射

一个类有两种状态(编译和运行),通常我们是在编译状态来获取类的信息,也就是new一个实例出来然后通过该实例来获取类内部的信息。若需要在类运行时动态的获取类的信息,则需要用到反射


内省

内省是通过反射来实现的,用BeanInfo来暴露一个bean的属性、方法和事件,以后我们就可以操纵该JavaBean的属性,其包括的主要类有:Introspector、BeanInfo、PropertyDescriptor








2. 使用流程


新建Bean对象

public class User {
    private int id;
    private String name;
    private String eamil;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEamil() {
        return eamil;
    }
    public void setEamil(String eamil) {
        this.eamil = eamil;
    }
    
    public User(int id, String name, String eamil) {
        super();
        this.id = id;
        this.name = name;
        this.eamil = eamil;
    }
}




测试

public class test {
    
    public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        
        // Introspector有方法来了解目标Java Bean支持的属性,事件和方法
        // BeanInfo提供bean的方法,属性,事件和其他功能的显式信息
        // PropertyDescriptor可导出一个属性
        
        User user = new User(1,"Howl","11111111@qq.com");
        
        // Introspector内有静态方法获取beanInfo,参数表示去除父类Object的方法,只保存User内部的方法
        BeanInfo  beanInfo = Introspector.getBeanInfo(User.class, Object.class);
        
        // beanInfo内部有方法获取PropertyDescriptor
        PropertyDescriptor[] propertys = beanInfo.getPropertyDescriptors();
        for(PropertyDescriptor value : propertys){
            // 全部属性,名字,类型,可读,可写方法
            System.out.println(value);
            
            // 通过PropertyDescriptor获取读方法,也有写方法
            Method method = value.getReadMethod();
            System.out.println(method.invoke(user));
            
        }
    }
}








自省(Introspector)

原文:https://www.cnblogs.com/Howlet/p/12349139.html

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