反射得到属性值与属性值
1.通过对象与属性名得到属性值
private static Object getFieldValue(Object object, String fieldName)
{
Object value = new Object();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String methodName = fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1);
Method method = object.getClass().getMethod("get" + methodName);
value = method.invoke(object);
if(java.util.Date.class.equals(method.getReturnType())){
if(value!=null){
value = df.format(value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
2.得到对象中所有属性
private static String[] getAllFields(Object object){
Field[] fields = object.getClass().getDeclaredFields();
List<String> list = new ArrayList<String>();
for(Field field : fields){
list.add(field.getName());
}
return list.toArray(new String[list.size()]);
}
3.设置属性值
// 该方法的参数列表是一个类的 类名、成员变量、给变量的赋值
public void setProperty(Object obj, String PropertyName, Object value)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
// 获取obj类的字节文件对象
Class c = obj.getClass();
// 获取该类的成员变量
Field f = c.getDeclaredField(PropertyName);
// 取消语言访问检查
f.setAccessible(true);
// 给变量赋值
f.set(obj, value);
}
---------------------
【转载,仅作分享,侵删】
作者:xinyuebaihe
原文:https://blog.csdn.net/xinyuebaihe/article/details/79386267
版权声明:本文为博主原创文章,转载请附上博文链接!
|
|