Java反射設(shè)置/獲取對象屬性值三種方式
本文總結(jié):Java 通過反射設(shè)置對象屬性值,或者獲取對象屬性值,編碼過程中反射結(jié)合泛型使用可以代碼復(fù)用,減少冗余代碼;
食用建議:配合場景案例食用更佳;
設(shè)置/獲取屬性
實(shí)體類對象:
@AllArgsConstructor
@NoArgsConstructor
@Data
public class StudentScore {
/**
* 名稱
*/
private String name;
/**
* 科目
*/
private String subject;
/**
* 成績
*/
private Integer score;
}
方式一
通過Field操作屬性:
public void method1() throws Exception {
Class<StudentScore> cls = StudentScore.class;
StudentScore obj = new StudentScore();
StudentScore obj2 = new StudentScore();
/*
* 設(shè)置屬性
*/
Field nameField = cls.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(obj, "張三");
Field subjectField = cls.getDeclaredField("subject");
subjectField.setAccessible(true);
subjectField.set(obj, "語文");
Field scoreField = cls.getDeclaredField("score");
scoreField.setAccessible(true);
scoreField.set(obj, 100);
/*
* 獲取屬性
*/
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
String s = Modifier.toString(field.getModifiers());
// 排除final修飾的屬性
if (!s.contains("final")) {
field.setAccessible(true);
// 通過filed獲取設(shè)置屬性
System.out.printf("獲取屬性值,當(dāng)前屬性:%s,值:%s%n", field.getName(), field.get(obj));
// obj對象屬性值賦值給obj2
field.set(obj2, field.get(obj));
}
}
System.out.println("method1 obj:" + JSONObject.toJSONString(obj));
System.out.println("method1 obj2:" + JSONObject.toJSONString(obj2));
}
運(yùn)行結(jié)果:

方式二
通過set方法:
public void method2() throws Exception {
Class<StudentScore> cls = StudentScore.class;
StudentScore obj = new StudentScore();
/*
* 設(shè)置屬性
*/
Method setName = cls.getMethod("setName", String.class);
setName.invoke(obj, "李四");
Method setSubject = cls.getMethod("setSubject", String.class);
setSubject.invoke(obj, "語文");
Method setScore = cls.getMethod("setScore", Integer.class);
setScore.invoke(obj, 114);
/*
* 獲取屬性
*/
Method getName = cls.getMethod("getName");
System.out.printf("獲取屬性值,當(dāng)前屬性:%s,值:%s%n", "name", getName.invoke(obj));
Method getSubject = cls.getMethod("getSubject");
System.out.printf("獲取屬性值,當(dāng)前屬性:%s,值:%s%n", "subject", getSubject.invoke(obj));
Method getScore = cls.getMethod("getScore");
System.out.printf("獲取屬性值,當(dāng)前屬性:%s,值:%s%n", "score", getScore.invoke(obj));
System.out.println("method2:" + JSONObject.toJSONString(obj));
}
運(yùn)行結(jié)果:

方式三
通過屬性名:
public void method3() throws Exception {
Class<StudentScore> cls = StudentScore.class;
StudentScore obj = new StudentScore();
/*
* 設(shè)置屬性
*/
PropertyDescriptor namePd = new PropertyDescriptor("name", cls);
Method writeMethod = namePd.getWriteMethod();
writeMethod.invoke(obj, "王五");
PropertyDescriptor subjectPd = new PropertyDescriptor("subject", cls);
Method subjectMethod = subjectPd.getWriteMethod();
subjectMethod.invoke(obj, "語文");
PropertyDescriptor scorePd = new PropertyDescriptor("score", cls);
Method scoreMethod = scorePd.getWriteMethod();
scoreMethod.invoke(obj, 127);
/*
* 獲取屬性
*/
Method nameRead = namePd.getReadMethod();
System.out.printf("獲取屬性值,當(dāng)前屬性:%s,值:%s%n", "name", nameRead.invoke(obj));
Method subjectRead = subjectPd.getReadMethod();
System.out.printf("獲取屬性值,當(dāng)前屬性:%s,值:%s%n", "subject", subjectRead.invoke(obj));
Method scoreRead = scorePd.getReadMethod();
System.out.printf("獲取屬性值,當(dāng)前屬性:%s,值:%s%n", "score", scoreRead.invoke(obj));
System.out.println("method3:" + JSONObject.toJSONString(obj));
}
運(yùn)行結(jié)果:

場景案例
場景:學(xué)生查詢自己的語文考試成績;

學(xué)生成績對象實(shí)體類:
/**
* 學(xué)生成績實(shí)體
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class StudentScore {
/**
* 名稱
*/
private String name;
/**
* 科目
*/
private String subject;
/**
* 成績
*/
private Integer score;
}學(xué)生對象實(shí)體類:
/**
* 學(xué)生-張三
*/
@Data
public class StudentZS extends StudentScore {
}
/**
* 學(xué)生-李四
*
*/
@Data
public class StudentLS extends StudentScore {
}
/**
* 學(xué)生-王五
*/
@Data
public class StudentWW extends StudentScore {
}測試:
@Test
public void testDemo() {
StudentZS student1 = new StudentZS();
student1.setName("張三");
scoreSystem(student1, StudentZS.class);
System.out.println("張三查詢成績結(jié)果:" + JSONObject.toJSONString(student1));
StudentLS student2 = new StudentLS();
student2.setName("李四");
scoreSystem(student2, StudentLS.class);
System.out.println("李四查詢成績結(jié)果:" + JSONObject.toJSONString(student2));
StudentWW student3 = new StudentWW();
student3.setName("王五");
scoreSystem(student3, StudentWW.class);
System.out.println("王五查詢成績結(jié)果:" + JSONObject.toJSONString(student3));
}
/**
* 成績系統(tǒng)
*
* @param t 學(xué)生
* @param cls 學(xué)生類
* @param <T> 泛型
*/
public <T> void scoreSystem(T t, Class<T> cls) {
// 給傳入對象賦值名稱
try {
Class<? super T> superclass = cls.getSuperclass();
Field nameField = superclass.getDeclaredField("name");
Type genericType = nameField.getGenericType();
String typeName = genericType.getTypeName();
assert "java.lang.String".equals(typeName);
nameField.setAccessible(true);
String studentName = nameField.get(t).toString();
int schoolReport = 0;
switch (studentName) {
case "張三":
schoolReport = 100;
break;
case "李四":
schoolReport = 114;
break;
case "王五":
schoolReport = 127;
break;
}
Field subjectField = superclass.getDeclaredField("subject");
subjectField.setAccessible(true);
subjectField.set(t, "語文");
Field scoreField = superclass.getDeclaredField("score");
scoreField.setAccessible(true);
scoreField.set(t, schoolReport);
} catch (Exception e) {
e.printStackTrace();
}
}
運(yùn)行結(jié)果:

總結(jié)
到此這篇關(guān)于Java反射設(shè)置/獲取對象屬性值三種方式的文章就介紹到這了,更多相關(guān)Java反射設(shè)置/獲取屬性值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入理解@component與@Configuration注解
這篇文章主要介紹了深入理解@component與@Configuration注解,從Spring3.0,@Configuration用于定義配置類,可替換xml配置文件,被注解的類內(nèi)部包含有一個或多個被@Bean注解的方法,這些方法將會被掃描,并用于構(gòu)建bean定義,初始化Spring容器,需要的朋友可以參考下2023-11-11
JAVA動態(tài)維度笛卡爾積輸出的實(shí)現(xiàn)
本文主要介紹了JAVA動態(tài)維度笛卡爾積輸出的實(shí)現(xiàn),通過動態(tài)生成笛卡爾積,可以方便地處理多維數(shù)據(jù)集,提高數(shù)據(jù)處理效率,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02
Java數(shù)據(jù)結(jié)構(gòu)之復(fù)雜度篇
算法復(fù)雜度分為時(shí)間復(fù)雜度和空間復(fù)雜度。其作用:?時(shí)間復(fù)雜度是度量算法執(zhí)行的時(shí)間長短;而空間復(fù)雜度是度量算法所需存儲空間的大小2022-01-01
SpringBoot?+?MyBatis-Plus構(gòu)建樹形結(jié)構(gòu)的幾種方式
在實(shí)際開發(fā)中,很多數(shù)據(jù)都是樹形結(jié)構(gòu),本文主要介紹了SpringBoot?+?MyBatis-Plus構(gòu)建樹形結(jié)構(gòu)的幾種方式,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
使用EasyPOI實(shí)現(xiàn)多sheet動態(tài)列導(dǎo)出
這篇文章主要為大家詳細(xì)介紹了如何使用EasyPOI根據(jù)指定時(shí)間范圍創(chuàng)建動態(tài)列,以及如何將數(shù)據(jù)組織成符合要求的格式并導(dǎo)出,感興趣的可以了解下2025-03-03

