• 自省(Introspector)




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


    1. 内省


    反射

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


    内省

    内省是通过反射来实现的,用BeanInfo来暴露一个bean的属性、方法和事件,以后我们就可以操纵该JavaBean的属性,其包括的主要类有:Introspector、BeanInfo、PropertyDescriptor。
    而其主要作用于面向抽象编程时,比如写框架时,其面向的类,对象并不存在,那么此时要用到反射和自省来调用getter/setter了





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




  • 相关阅读:
    windows端口占用处理方法
    【接口】接口测试常见响应码类型(二)
    【接口】SpringBoot+接口开发(一)
    【java+selenium3】Tesseract-OCR识别图片验证码 (十六)
    java读写Txt文件
    【java+selenium3】自动化基础小结+selenium原理揭秘 (十七)
    【java+selenium3】自动化cookie操作+图形验证码处理 (十五)
    【java+selenium3】自动化截图 (十四)
    【Java+selenium3】 Firefox/ IE/ Chrome主流浏览器自动化环境搭建(一)
    【java+selenium3】自动化处理文件上传 (十三)
  • 原文地址:https://www.cnblogs.com/Howlet/p/12349139.html
Copyright © 2020-2023  润新知