代码:
// 通过属性获取传入对象的指定属性的值
public String getValueByPropName(Student student, String propName) {
String value = null;
try {
// 通过属性获取对象的属性
Field field = student.getClass().getDeclaredField(propName);
// 对象的属性的访问权限设置为可访问
field.setAccessible(true);
// 获取属性的对应的值
value = field.get(student).toString();
} catch (Exception e) {
return null;
}
return value;
}
本文介绍了一种使用Java反射机制获取对象特定属性值的方法。通过getClass().getDeclaredField()方法找到对象的指定属性,然后设置该属性为可访问,并通过field.get()获取属性值。
616

被折叠的 条评论
为什么被折叠?



