import Java(Java教程 Java培訓 ).lang.reflect.Method;
import java.lang.reflect.Field;
import java.beans.PropertyDescriptor;
public class PropertyUtil {
public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) {
StringBuffer sb = new StringBuffer(); //構建一個可變字符串用來構建方法名稱
Method setMethod = null;
Method getMethod = null;
PropertyDescriptor pd = null;
try {
Field f = clazz.getDeclaredField(propertyName); //根據字段名來獲取字段
if (f != null) {
//構建方法的后綴
String methodEnd = propertyName.substring(0, 1)。toUpperCase() + propertyName.substring(1);
sb.append(“set” + methodEnd); //構建set方法
setMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ f.getType() });
sb.delete(0, sb.length()); //清空整個可變字符串
sb.append(“get” + methodEnd); //構建get方法
//構建get 方法
getMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ });
//構建一個屬性描述器 把對應屬性 propertyName 的 get 和 set 方法保存到屬性描述器中
pd = new PropertyDescriptor(propertyName, getMethod, setMethod);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return pd;
}
public static void setProperty(Object obj,String propertyName,Object value){
Class clazz = obj.getClass();//獲取對象的類型
PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);//獲取 clazz 類型中的 propertyName 的屬性描述器
Method setMethod = pd.getWriteMethod();//從屬性描述器中獲取 set 方法
try {
setMethod.invoke(obj, new Object[]{value});//調用 set 方法將傳入的value值保存屬性中去
} catch (Exception e){
e.printStackTrace();
}
}
public static Object getProperty(Object obj, String propertyName){
Class clazz = obj.getClass();//獲取對象的類型
PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);//獲取 clazz 類型中的 propertyName 的屬性描述器
Method getMethod = pd.getReadMethod();//從屬性描述器中獲取 get 方法
Object value =null ;
try {
value = getMethod.invoke(clazz, new Object[]{});//調用方法獲取方法的返回值
} catch (Exception e) {
e.printStackTrace();
}
return value;//返回值
}
}