Java反射設(shè)置/獲取對(duì)象屬性值三種方式
本文總結(jié):Java 通過(guò)反射設(shè)置對(duì)象屬性值,或者獲取對(duì)象屬性值,編碼過(guò)程中反射結(jié)合泛型使用可以代碼復(fù)用,減少冗余代碼;
食用建議:配合場(chǎng)景案例食用更佳;
設(shè)置/獲取屬性
實(shí)體類(lèi)對(duì)象:
@AllArgsConstructor @NoArgsConstructor @Data public class StudentScore { /** * 名稱(chēng) */ private String name; /** * 科目 */ private String subject; /** * 成績(jī) */ private Integer score; }
方式一
通過(guò)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, "語(yǔ)文"); 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); // 通過(guò)filed獲取設(shè)置屬性 System.out.printf("獲取屬性值,當(dāng)前屬性:%s,值:%s%n", field.getName(), field.get(obj)); // obj對(duì)象屬性值賦值給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é)果:
方式二
通過(guò)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, "語(yǔ)文"); 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é)果:
方式三
通過(guò)屬性名:
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, "語(yǔ)文"); 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é)果:
場(chǎng)景案例
場(chǎng)景:學(xué)生查詢(xún)自己的語(yǔ)文考試成績(jī);
學(xué)生成績(jī)對(duì)象實(shí)體類(lèi):
/** * 學(xué)生成績(jī)實(shí)體 */ @AllArgsConstructor @NoArgsConstructor @Data public class StudentScore { /** * 名稱(chēng) */ private String name; /** * 科目 */ private String subject; /** * 成績(jī) */ private Integer score; }
學(xué)生對(duì)象實(shí)體類(lèi):
/** * 學(xué)生-張三 */ @Data public class StudentZS extends StudentScore { } /** * 學(xué)生-李四 * */ @Data public class StudentLS extends StudentScore { } /** * 學(xué)生-王五 */ @Data public class StudentWW extends StudentScore { }
測(cè)試:
@Test public void testDemo() { StudentZS student1 = new StudentZS(); student1.setName("張三"); scoreSystem(student1, StudentZS.class); System.out.println("張三查詢(xún)成績(jī)結(jié)果:" + JSONObject.toJSONString(student1)); StudentLS student2 = new StudentLS(); student2.setName("李四"); scoreSystem(student2, StudentLS.class); System.out.println("李四查詢(xún)成績(jī)結(jié)果:" + JSONObject.toJSONString(student2)); StudentWW student3 = new StudentWW(); student3.setName("王五"); scoreSystem(student3, StudentWW.class); System.out.println("王五查詢(xún)成績(jī)結(jié)果:" + JSONObject.toJSONString(student3)); } /** * 成績(jī)系統(tǒng) * * @param t 學(xué)生 * @param cls 學(xué)生類(lèi) * @param <T> 泛型 */ public <T> void scoreSystem(T t, Class<T> cls) { // 給傳入對(duì)象賦值名稱(chēng) 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, "語(yǔ)文"); 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è)置/獲取對(duì)象屬性值三種方式的文章就介紹到這了,更多相關(guān)Java反射設(shè)置/獲取屬性值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入理解@component與@Configuration注解
這篇文章主要介紹了深入理解@component與@Configuration注解,從Spring3.0,@Configuration用于定義配置類(lèi),可替換xml配置文件,被注解的類(lèi)內(nèi)部包含有一個(gè)或多個(gè)被@Bean注解的方法,這些方法將會(huì)被掃描,并用于構(gòu)建bean定義,初始化Spring容器,需要的朋友可以參考下2023-11-11JAVA動(dòng)態(tài)維度笛卡爾積輸出的實(shí)現(xiàn)
本文主要介紹了JAVA動(dòng)態(tài)維度笛卡爾積輸出的實(shí)現(xiàn),通過(guò)動(dòng)態(tài)生成笛卡爾積,可以方便地處理多維數(shù)據(jù)集,提高數(shù)據(jù)處理效率,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02Java數(shù)據(jù)結(jié)構(gòu)之復(fù)雜度篇
算法復(fù)雜度分為時(shí)間復(fù)雜度和空間復(fù)雜度。其作用:?時(shí)間復(fù)雜度是度量算法執(zhí)行的時(shí)間長(zhǎng)短;而空間復(fù)雜度是度量算法所需存儲(chǔ)空間的大小2022-01-01SpringBoot?+?MyBatis-Plus構(gòu)建樹(shù)形結(jié)構(gòu)的幾種方式
在實(shí)際開(kāi)發(fā)中,很多數(shù)據(jù)都是樹(shù)形結(jié)構(gòu),本文主要介紹了SpringBoot?+?MyBatis-Plus構(gòu)建樹(shù)形結(jié)構(gòu)的幾種方式,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08使用EasyPOI實(shí)現(xiàn)多sheet動(dòng)態(tài)列導(dǎo)出
這篇文章主要為大家詳細(xì)介紹了如何使用EasyPOI根據(jù)指定時(shí)間范圍創(chuàng)建動(dòng)態(tài)列,以及如何將數(shù)據(jù)組織成符合要求的格式并導(dǎo)出,感興趣的可以了解下2025-03-03輕松搞定SpringBoot JPA使用配置過(guò)程詳解
Spring Boot是由Pivotal團(tuán)隊(duì)提供的全新框架,該框架使用了特定的方式來(lái)進(jìn)行配置,它默認(rèn)配置了很多框架的使用方式,就像 Maven整合了所有的Jar包,Spring Boot 整合了所有的框架2021-06-06