{"thing1":{"value":"咔咔618养车节"},"thing16":{"value":"人工洗车特惠提前购¥29.9元‼"}}使用反射用java写出来
时间: 2023-07-02 13:20:51 浏览: 157
你需要使用Java的反射机制来动态操作对象的属性值。具体实现代码如下:
```java
import java.lang.reflect.Field;
public class ReflectExample {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
// 创建一个包含thing1和thing16属性的对象
ExampleObject obj = new ExampleObject("原始值", "原始值");
// 反射获取thing1属性
Field thing1Field = obj.getClass().getDeclaredField("thing1");
thing1Field.setAccessible(true); // 设置为可访问
Object thing1Value = thing1Field.get(obj); // 获取属性值
// 反射获取thing16属性
Field thing16Field = obj.getClass().getDeclaredField("thing16");
thing16Field.setAccessible(true); // 设置为可访问
Object thing16Value = thing16Field.get(obj); // 获取属性值
// 修改thing1和thing16的值
thing1Field.set(thing1Value, "咔咔618养车节");
thing16Field.set(thing16Value, "人工洗车特惠提前购¥29.9元‼");
// 打印修改后的值
System.out.println(obj.thing1.value);
System.out.println(obj.thing16.value);
}
}
class ExampleObject {
public Thing thing1;
public Thing thing16;
public ExampleObject(String thing1Value, String thing16Value) {
this.thing1 = new Thing(thing1Value);
this.thing16 = new Thing(thing16Value);
}
}
class Thing {
public String value;
public Thing(String value) {
this.value = value;
}
}
```
输出结果:
```
咔咔618养车节
人工洗车特惠提前购¥29.9元‼
```
阅读全文