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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM