package com.zhoushun;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.beans.PropertyDescriptor;
public class PropertyUtil {
@SuppressWarnings("unchecked")
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);
setMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ f.getType() });
sb.delete(0, sb.length());
sb.append("get" + methodEnd);
getMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ });
pd = new PropertyDescriptor(propertyName, getMethod, setMethod);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return pd;
}
@SuppressWarnings("unchecked")
public static void setProperty(Object obj,String propertyName,Object value){
Class clazz = obj.getClass();
PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);
Method setMethod = pd.getWriteMethod();
try {
setMethod.invoke(obj, new Object[]{value});
}catch (Exception e){
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static Object getProperty(Object obj, String propertyName){
Class clazz = obj.getClass();
PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);
Method getMethod = pd.getReadMethod();
Object value =null ;
try {
value = getMethod.invoke(clazz, new Object[]{});
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
}