Java使用反射通过对象属性获取属性的值

代码:

    // 通过属性获取传入对象的指定属性的值
    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;
    }
原文地址:https://www.cnblogs.com/Big-Boss/p/9753348.html