反射獲取類的 屬性名(name) 和值(value)
1.新建物件user:
package com.entity;
public class User {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
2 . * 獲取類中寫 屬性名 陣列
/**
* * 獲取屬性名陣列
*
* @param person
* @return
*/
public static String[] getFiledName(User user) {
Field[] fields = user.getClass().getDeclaredFields();
String[] fieldNamStrings = new String[fields.length];
for (int i = 0; i < fieldNamStrings.length; i++) {
fieldNamStrings[i] = fields[i].getName();
}
return fieldNamStrings;
}
3. * 根據 類中的 屬性名字 獲取值 (value)
/**
*
* @Description 根據屬性名 獲取值(value)
* @param name
* @param user
* @return
* @throws IllegalAccessException
*/
public static Object getFieldValueByName(String name, User user) throws IllegalAccessException {
String firstletter = name.substring(0, 1).toUpperCase();
String getter = "get" + firstletter + name.substring(1);
Method method;
Object value;
try {
method = user.getClass().getMethod(getter, new Class[] {});
value = method.invoke(user, new User[] {});
return value;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
4. 編寫 測試方法
public static void main(String[] args) {
User user = new User();
user.setName("zhangsan");
user.setId("1");
String[] fieldNames = getFiledName(user);
for (int j = 0; j < fieldNames.length; j++) { // 遍歷所有屬性
String name = fieldNames[j]; // 獲取屬性的名字
Object value;
try {
value = getFieldValueByName(name, user);
// 根據屬性獲取value值
// 載入裁決書模組設定實體類
System.out.println("key="+name);
System.out.println("value="+value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
5. 執行結果 :
key=id
value=1
key=name
value=zhangsan
--------------------------------------------------------------------------------------------------------------------------------------------------------
生活賦予我們一種巨大的和無限高貴的禮品,這就是青春:充滿著力量,充滿著期待志願,充滿著求知和鬥爭的志向,充滿著希望信心和青春。 —— 奧斯特洛夫斯基