Java反射設置/獲取對象屬性值三種方式
更新時間:2023年11月07日 09:30:14 作者:zhuzicc
這篇文章主要給大家介紹了關于Java反射設置/獲取對象屬性值的三種方式,反射機制的用途非常多,比如獲取方法,屬性名和屬性值等,甚至可以獲取標簽等標簽屬性,需要的朋友可以參考下
本文總結:Java 通過反射設置對象屬性值,或者獲取對象屬性值,編碼過程中反射結合泛型使用可以代碼復用,減少冗余代碼;
食用建議:配合場景案例食用更佳;
設置/獲取屬性
實體類對象:
@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(); /* * 設置屬性 */ 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獲取設置屬性 System.out.printf("獲取屬性值,當前屬性:%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)); }
運行結果:
方式二
通過set方法:
public void method2() throws Exception { Class<StudentScore> cls = StudentScore.class; StudentScore obj = new StudentScore(); /* * 設置屬性 */ 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("獲取屬性值,當前屬性:%s,值:%s%n", "name", getName.invoke(obj)); Method getSubject = cls.getMethod("getSubject"); System.out.printf("獲取屬性值,當前屬性:%s,值:%s%n", "subject", getSubject.invoke(obj)); Method getScore = cls.getMethod("getScore"); System.out.printf("獲取屬性值,當前屬性:%s,值:%s%n", "score", getScore.invoke(obj)); System.out.println("method2:" + JSONObject.toJSONString(obj)); }
運行結果:
方式三
通過屬性名:
public void method3() throws Exception { Class<StudentScore> cls = StudentScore.class; StudentScore obj = new StudentScore(); /* * 設置屬性 */ 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("獲取屬性值,當前屬性:%s,值:%s%n", "name", nameRead.invoke(obj)); Method subjectRead = subjectPd.getReadMethod(); System.out.printf("獲取屬性值,當前屬性:%s,值:%s%n", "subject", subjectRead.invoke(obj)); Method scoreRead = scorePd.getReadMethod(); System.out.printf("獲取屬性值,當前屬性:%s,值:%s%n", "score", scoreRead.invoke(obj)); System.out.println("method3:" + JSONObject.toJSONString(obj)); }
運行結果:
場景案例
場景:學生查詢自己的語文考試成績;
學生成績對象實體類:
/** * 學生成績實體 */ @AllArgsConstructor @NoArgsConstructor @Data public class StudentScore { /** * 名稱 */ private String name; /** * 科目 */ private String subject; /** * 成績 */ private Integer score; }
學生對象實體類:
/** * 學生-張三 */ @Data public class StudentZS extends StudentScore { } /** * 學生-李四 * */ @Data public class StudentLS extends StudentScore { } /** * 學生-王五 */ @Data public class StudentWW extends StudentScore { }
測試:
@Test public void testDemo() { StudentZS student1 = new StudentZS(); student1.setName("張三"); scoreSystem(student1, StudentZS.class); System.out.println("張三查詢成績結果:" + JSONObject.toJSONString(student1)); StudentLS student2 = new StudentLS(); student2.setName("李四"); scoreSystem(student2, StudentLS.class); System.out.println("李四查詢成績結果:" + JSONObject.toJSONString(student2)); StudentWW student3 = new StudentWW(); student3.setName("王五"); scoreSystem(student3, StudentWW.class); System.out.println("王五查詢成績結果:" + JSONObject.toJSONString(student3)); } /** * 成績系統(tǒng) * * @param t 學生 * @param cls 學生類 * @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(); } }
運行結果:
總結
到此這篇關于Java反射設置/獲取對象屬性值三種方式的文章就介紹到這了,更多相關Java反射設置/獲取屬性值內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
深入理解@component與@Configuration注解
這篇文章主要介紹了深入理解@component與@Configuration注解,從Spring3.0,@Configuration用于定義配置類,可替換xml配置文件,被注解的類內部包含有一個或多個被@Bean注解的方法,這些方法將會被掃描,并用于構建bean定義,初始化Spring容器,需要的朋友可以參考下2023-11-11SpringBoot?+?MyBatis-Plus構建樹形結構的幾種方式
在實際開發(fā)中,很多數據都是樹形結構,本文主要介紹了SpringBoot?+?MyBatis-Plus構建樹形結構的幾種方式,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-08-08