代碼:
// 通過屬性獲取傳入對象的指定屬性的值 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; }