其實,我也不太懂內省是什麼。估計是將數據封裝到對象當中那樣子吧!等有時間再來詳細瞭解它吧…
所以,我就直接甩代碼吧:
package com.descriptor;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
/**
* Description:
* 內省
*
* @author lee
* */
public class DescriptorDemo {
/**
* Description:
* 使用屬性描述器,獲取對象的setter或getter方法
*
* */
public static void test1()throws Exception{
Person p = new Person();
//屬性描述器
PropertyDescriptor descriptor = new PropertyDescriptor("id",Person.class);
//獲取屬性setter方法
Method setMethod = descriptor.getWriteMethod();
//獲取屬性個體特然方法
Method getMethod = descriptor.getReadMethod();
//調用setter方法設置id值
setMethod.invoke(p, 1);
System.out.println(p.getId());
}
/**
* Description:
* 獲取所有屬性描述器
*
* */
public static void test2()throws Exception {
//Intropect內省類
BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
//通過BeanInfo獲取所有屬性描述器
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
//輸出所有屬性描述器
for(PropertyDescriptor descriptor:descriptors){
System.out.println(descriptor);
}
}
/**
* Description:
* 主方法
*
* */
public static void main(String[] args)throws Exception {
test1();
test2();
}
}
/**
* Description:
* 一個javabean類
*
* @author lee
* */
class Person{
private int id;
private String name;
/**
* Description:
* 默認構造器
*
* */
public Person(){}
//getter,setter方法
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;
}
}
任性!不解釋!(手動滑稽)