简体   繁体   English

如果所有属性的值不为 null 或为空,如何将所有属性的值从对象的一个​​实例复制到另一个实例

[英]How to copy values of all attributes from one instance of an object to another if they are not null or empty

Given a class Person:给定一个 Person 类:

String name;
String surname;
String id;
String address;

I have an object obj1 with the following values:我有一个具有以下值的对象obj1

name="Name"
surname=null
id="ABC123"
address="Here"

Through an api call I get the following json:通过 api 调用,我得到以下 json:

{
   "name":"John",
   "surname":"Doe",
   "id":"A1B2C3"
}

which gets mapped into an object obj2 like this:它被映射到一个对象obj2如下所示:

name="John"
surname="Doe"
id="A1B2C3"
address=null

I want to copy all non-null (or empty string) values of obj2 into obj1 so the final result is this:我想将obj2所有非空(或空字符串)值复制到obj1因此最终结果是这样的:

name="John"
surname="Doe"
id="A1B2C3"
address="Here"

I have two problems.我有两个问题。 The first one is that I don't want to have to manually type the get/set call for each attribute of the object.第一个是我不想为对象的每个属性手动键入 get/set 调用。 The second problem, is that I want the method to work for any type of object with no or minimal changes.第二个问题是,我希望该方法适用于任何类型的对象,而无需更改或更改最少。

At the very least, I need the first problem solved.至少,我需要解决第一个问题。 The second one is optional, but would be great to learn a solution too.第二个是可选的,但也可以学习解决方案。

You can use reflection to get all the instance fields and use Field#set to copy over non-null values.您可以使用反射来获取所有实例字段并使用Field#set来复制非空值。

try {
    for (Field field : Person.class.getDeclaredFields()) {
        if (!Modifier.isStatic(field.getModifiers())) {
            field.setAccessible(true);
            Object val = field.get(obj2);
            if (val != null) {
                field.set(obj1, val);
            }
        }
    }
    System.out.println(obj1);
} catch (IllegalAccessException e) {
    // Handle exception
}

Demo演示

public static void main(String[] args) {
    MyClass obj1 = new MyClass(1,"1");
    MyClass obj2 = new MyClass(2,"2");
    System.out.println(obj2);
    copy(obj1, obj2);
    System.out.println(obj2);
}

public static MyClass copy(MyClass obj1, MyClass obj2){
    Arrays.stream(obj1.getClass().getDeclaredFields()).forEach(f -> {
        try {
             f.set(obj2, f.get(obj1));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    });
    return obj2;
}

static class MyClass {
    int myInt;
    String myString;
    String emptyString = null;

    public MyClass(int myInt, String myString) {
        this.myInt = myInt;
        this.myString = myString;
    }

    @Override
    public String toString() {
        return "MyClass{" +
                "myInt=" + myInt +
                ", myString='" + myString + '\'' +
                ", emptyString='" + emptyString + '\'' +
                '}';
    }
}

in case you have private fields you can use如果您有可以使用的私有字段

f.setAccessible(true);

but I don't suggest that.但我不建议这样做。

Reading your question, seems like, you have two classes, in two distinct projects, which, exchange information in json.阅读您的问题,似乎您在两个不同的项目中有两个类,它们在 json 中交换信息。

So, It is easy if you can use Jackson(default in spring)所以,如果你可以使用杰克逊很容易(春季默认)

You could annotate the target class with the annotation of jackson @JsonInclude(JsonInclude.Include.NON_NULL)您可以使用 jackson @JsonInclude(JsonInclude.Include.NON_NULL)的注释来注释目标类

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java:将属性从一个对象实例复制到另一个对象实例 - Java: Copy attributes from one object instance to another? 从一个实例到另一个线程的非零/非空属性的另一个副本,嵌套方法/Java - Yet another copy of non-zero/non-null attributes from one instance to another thread, nested approach / Java 从一个 object 复制 not null and not empty fields 到 java 中的另一个 object 相同类型(对象是相同类型) - Copy not null and not empty fields from one object to another object of the same type(Objects are same type) in java 如何将所有值从一个JSONObject复制到另一个? - How to copy all the values from one JSONObject to another? 将大多数属性从一个 class object 复制到另一个 class - Copy most attributes from one class object to another class 反射将非null属性从一个对象复制到另一个BeanUtils - reflection copy non null properties from one object to another BeanUtils Java中如何将文件属性从一个文件复制到另一个文件? - How to copy file attributes from one file to another in Java? How do I remove all null and empty string values from an object in json java android from retrofit? - How do I remove all null and empty string values from an object in json java android from retrofit? 通过反射将一个 class 中字段的所有值复制到另一个 - Copy all values from fields in one class to another through reflection 将一个 class 中字段的所有值复制到另一个 class - Copy all values from fields in one class to another class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM