随机名言

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




posted @ 2020-02-23 12:16  Howlet  阅读(151)  评论(0编辑  收藏  举报

Copyright © By Howl