day27(反射之内省机制)

  内省

      内省:底层是使用反射机制实现的,是对于反射的进一步封装。

        反射:通过类名来获取类中的所有属性和方法及类中的所有隐藏的方法。

        内省:通过一个标准类(javabean类)来获取bean中的字段、get/set方法。

JavaBean:就是一个满足了特定格式的Java类:
* 需要提供无参数的构造方法:
* 属性私有
* 对私有的属性提供public的get/set方法.

      创建一个Student标准类

public class Student {
	private String name;
	private int age;
	//private String sax;
	public String getSax() {
		return null;
	}
	public void setSax(String sax) {
		//this.sax = sax;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

      测试类

    public static void main(String[] args) throws IntrospectionException {
		//获取的bean信息
		BeanInfo beanInfo = Introspector.getBeanInfo(Student.class);
		//回去bean的属性描述
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
			//获取属性名字(只要提供get/set属性时)
			System.out.println(propertyDescriptor.getName());
			//获得get方法
			//System.out.println(propertyDescriptor.getReadMethod().getName());
			// 获得set方法
			//propertyDescriptor.getWriteMethod();.
		}
	}

  

      

    

原文地址:https://www.cnblogs.com/fjkgrbk/p/introspection.html