java 反射给对象新增属性并赋值工具类
时间: 2024-02-19 16:26:53 浏览: 233
以下是示例代码,可以通过反射给对象新增属性并赋值:
```java
import java.lang.reflect.Field;
public class ReflectUtil {
public static void setFieldValue(Object obj, String fieldName, Object fieldValue) throws Exception {
Class<?> clazz = obj.getClass();
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, fieldValue);
}
}
```
使用示例:
```java
public class User {
private String name;
private int age;
// getter and setter
}
public class Main {
public static void main(String[] args) throws Exception {
User user = new User();
ReflectUtil.setFieldValue(user, "name", "Tom");
ReflectUtil.setFieldValue(user, "age", 18);
System.out.println(user.getName()); // Tom
System.out.println(user.getAge()); // 18
}
}
```
阅读全文