往对象里面新增属性 遇到相同的属性就重新赋值
时间: 2023-12-13 09:56:22 浏览: 52
可以使用对象的赋值操作符(=)来新增属性。如果原先已有相同的属性,则会被重新赋值。例如:
```javascript
let obj = {name: 'Alice', age: 25};
obj.name = 'Bob'; // 修改属性值
obj.city = 'New York'; // 新增属性
obj.age = 30; // 修改属性值
console.log(obj); // 输出 {name: 'Bob', age: 30, city: 'New York'}
```
相关问题
java 反射给对象新增属性并赋值
Java反射可以通过调用set方法给对象新增属性并赋值。具体步骤如下:
1. 获取Class对象,可以使用Class.forName()方法或者类的.class属性获取。
2. 使用Class对象的getDeclaredField()方法获取指定名称的属性对象。
3. 设置属性对象的访问权限,使用Field对象的setAccessible(true)方法。
4. 使用Field对象的set()方法给属性赋值。
示例代码如下:
```
public class Person {
private String name;
private int age;
// getter and setter
}
public static void main(String[] args) throws Exception {
// 获取Person类的Class对象
Class<?> clazz = Class.forName("com.example.Person");
// 创建Person对象
Person person = new Person();
// 获取name属性的Field对象
Field nameField = clazz.getDeclaredField("name");
// 设置属性的访问权限
nameField.setAccessible(true);
// 给属性赋值
nameField.set(person, "张三");
// 获取age属性的Field对象
Field ageField = clazz.getDeclaredField("age");
// 设置属性的访问权限
ageField.setAccessible(true);
// 给属性赋值
ageField.set(person, 18);
// 输出属性值
System.out.println(person.getName()); // 输出:张三
System.out.println(person.getAge()); // 输出:18
}
```
java 反射给对象新增属性并赋值工具类
以下是示例代码,可以通过反射给对象新增属性并赋值:
```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
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)