下面看下代碼,具體代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
package utils.copyProperty; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; public class CopyProperty { public static PropertyDescriptor[] getPropertyDescriptor(Class<?> clz) throws Exception { PropertyDescriptor[] propertyDescriptorsFull = Introspector.getBeanInfo(clz).getPropertyDescriptors(); PropertyDescriptor[] ps = new PropertyDescriptor[propertyDescriptorsFull.length - 1 ]; int index = 0 ; for (PropertyDescriptor p : propertyDescriptorsFull) { if (!p.getName().equals( "class" )) { ps[index++] = p; } } return ps; } public static <T> T setPropertyValue(T t,String propertyName,Object value){ try { PropertyDescriptor[] pdArr = getPropertyDescriptor(t.getClass()); PropertyDescriptor myPD = null ; for (PropertyDescriptor p : pdArr) { //類屬性與傳入屬性對比,為了統一都轉小寫 if (p.getName().toLowerCase().equals(propertyName.toLowerCase())){ //獲取需要修改屬性 myPD = p; break ; } } //根據需要修改屬性,修改屬性值 if (myPD!= null ){ Method writeMethod = myPD.getWriteMethod(); if (myPD.getPropertyType().getName().equals( "java.lang.String" )) { writeMethod.invoke(t, value.toString()); } else { writeMethod.invoke(t, value); } } } catch (Exception e){ e.printStackTrace(); } return t; } public static <T>Collection<T> setPropertyValue(Collection<T> coll,String propertyName,Object value) { if (coll!= null ) for (T t : coll){ setPropertyValue(t,propertyName,value); } return coll; } public static void main(String args[]) throws Exception{ ArrayList<Student> students= new ArrayList(); Student student= new Student(); Student student1= new Student(); students.add(student); students.add(student1); for (Student stu:students){ System.out.println( "賦值之前:" +stu.getValidStatus()); } //修改validStatus為0 CopyProperty.setPropertyValue(students, "validStatus" , "0" ); for (Student stu:students){ System.out.println( "賦值之后:" +stu.getValidStatus()); } } public static class Student{ private String name ; private String sex; private String validStatus= "1" ; public String getName() { return name; } public void setName(String name) { this .name = name; } public String getSex() { return sex; } public void setSex(String sex) { this .sex = sex; } public String getValidStatus() { return validStatus; } public void setValidStatus(String validStatus) { this .validStatus = validStatus; } } } |
把student的validStatus狀態都修改為0,測試效果如下:
到此這篇關于如何利用反射批量修改java類某一屬性的文章就介紹到這了,更多相關批量修改java類某一屬性內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/jungeCSND/article/details/107529497