在Java中,可以使用反射机制来实现对象属性的赋值。如果要排除空属性赋值,可以在赋值时判断属性值是否为空,如果为空则跳过不赋值。具体实现如下:
import java.lang.reflect.Field;
public class ObjectAssign {
public static void assign(Object obj1, Object obj2) throws IllegalAccessException {
// 获取obj1和obj2的Class对象
Class<?> clazz1 = obj1.getClass();
Class<?> clazz2 = obj2.getClass();
// 获取obj2的所有属性
Field[] fields2 = clazz2.getDeclaredFields();
// 遍历obj2的所有属性,将非空属性值赋值给相应的obj1属性
for (Field field2 : fields2) {
// 排除静态属性和final属性
if (java.lang.reflect.Modifier.isStatic(field2.getModifiers()) ||
java.lang.reflect.Modifier.isFinal(field2.getModifiers())) {
continue;
}
// 获取obj2属性的名称和值
field2.setAccessible(true);
Object value2 = field2.get(obj2);
if (value2 == null) { // 如果属性值为空,则跳过不赋值
continue;
}
// 获取obj1中对应属性的Field对象,并赋值
try {
Field field1 = clazz1.getDeclaredField(field2.getName());
field1.setAccessible(true);
field1.set(obj1, value2);
} catch (NoSuchFieldException e) {
// 如果obj1中不存在对应的属性,则忽略该属性
}
}
}
public static void main(String[] args) throws IllegalAccessException {
// 测试代码
User user1 = new User(1, "Tom", 18, "123456");
User user2 = new User(2, "Jerry", null, "654321");
assign(user1, user2);
System.out.println(user1);
}
}
class User {
private int id;
private String name;
private Integer age;
private String password;
public User(int id, String name, Integer age, String password) {
this.id = id;
this.name = name;
this.age = age;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", password='" + password + '\'' +
'}';
}
}