【Java】+反射2+设置属性/成员变量 的值

扩展链接:【Java】+反射1+获取属性/成员变量 的名称及类型

一、封装的通用方法(可直接用)

 1 /**
 2      * 功能:通过反射 设置指定类对象中的 指定属性的值
 3      *
 4      * @param obj           类对象
 5      * @param propertyName  要设置的属性名
 6      * @param propertyvalue 要设置的属性的值
 7      */
 8     public void set(Object obj, String propertyName, Object propertyvalue) {
 9         try {
10             // step1 获取属性指针
11             Field declaredField = obj.getClass().getDeclaredField(propertyName);
12             // step2 设置属性可访问
13             declaredField.setAccessible(true);
14             // step3 设置属性的值
15             declaredField.set(obj, propertyvalue);
16         } catch (NoSuchFieldException | IllegalAccessException e) {
17             e.printStackTrace();
18         }
19     }

 

二、示例

 

 

三、完整代码

 1 package com.alipay.ipay.gn.icdpcore.tool;
 2 
 3 import org.testng.annotations.Test;
 4 
 5 import java.lang.reflect.Field;
 6 
 7 /**
 8  * @author 
 9  * @version 1.0
10  * @time 2019/11/23 13:27
11  */
12 public class SetPropertyValue {
13     private String str = "abc";
14     private int number = 66;
15     private boolean aa = true;
16 
17     /**
18      * 功能:通过反射 设置指定类对象中的 指定属性的值
19      *
20      * @param obj           类对象
21      * @param propertyName  要设置的属性名
22      * @param propertyvalue 要设置的属性的值
23      */
24     public void set(Object obj, String propertyName, Object propertyvalue) {
25         try {
26             // step1 获取属性指针
27             Field declaredField = obj.getClass().getDeclaredField(propertyName);
28             // step2 设置属性可访问
29             declaredField.setAccessible(true);
30             // step3 设置属性的值
31             declaredField.set(obj, propertyvalue);
32         } catch (NoSuchFieldException | IllegalAccessException e) {
33             e.printStackTrace();
34         }
35     }
36 
37     @Test
38     public void test() {
39         SetPropertyValue spv = new SetPropertyValue();
40         System.out.println(String.format("设置前:str=%s number=%s aa=%s", spv.getStr(), spv.getNumber(), spv.isAa()));
41 
42         spv.set(spv, "str", "哈哈");
43         spv.set(spv, "number", 888888);
44         spv.set(spv, "aa", false);
45 
46         System.out.println(String.format("设置后:str=%s number=%s aa=%s", spv.getStr(), spv.getNumber(), spv.isAa()));
47     }
48 
49 
50     public String getStr() {
51         return str;
52     }
53 
54     public void setStr(String str) {
55         this.str = str;
56     }
57 
58     public int getNumber() {
59         return number;
60     }
61 
62     public void setNumber(int number) {
63         this.number = number;
64     }
65 
66     public boolean isAa() {
67         return aa;
68     }
69 
70     public void setAa(boolean aa) {
71         this.aa = aa;
72     }
73 }
posted @ 2019-11-23 15:56  淡怀  阅读(1239)  评论(0编辑  收藏  举报