【Java中的內省】:
用來獲得JavaBean的屬性及屬性的get或set方法
JavaBean就是一個特定格式的Java類:
需要提供無參數的構造方法
屬性私有
對私有的屬性提供public的GET、Set方法
public class MyBeanUtils {
public static void populate(Object object,Map<String, String[] >map) throws Exception{
// 獲得類的所有屬性的名稱
BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
// 獲得類中的所有屬性:
PropertyDescriptor[] propertyDescriptor = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor2 : propertyDescriptor) {
if (map.containsKey(propertyDescriptor2.getName())) {
Method method = propertyDescriptor2.getWriteMethod();
// 執行Set方法
method.invoke(object, map.get(propertyDescriptor2.getName())[0]);
}
}
}
}