私の目的は、あるオブジェクトのフィールドを別のオブジェクトにコピーすることですが、nullではないフィールドのみをコピーします。明示的に割り当てたくありません。より一般的なソリューションは、特定のフィールドのみの提供を許可するREST APIでPATCHを実装する場合など、非常に便利で保守が容易です。
私はこの同様のスレッドを見て、ここからいくつかのアイデアを実装しようとしています:オブジェクトから別のオブジェクトにnull以外のプロパティをコピーするためのヘルパー?(Java)
ただし、プログラムの実行後、オブジェクトは変更されません。
たとえば、作成したクラスの例を次に示します。
class Person {
String name;
int age;
Pet friend;
public Person() {
}
public Person(String name, int age, Pet friend) {
this.name = name;
this.age = age;
this.friend = friend;
}
// getters and setters here
}
class Pet {
String name;
int age;
public Pet(String name, int age) {
this.name = name;
this.age = age;
}
// getters and setters here
}
これが私のオーバーライドされたcopyPropertyメソッドです:
import org.apache.commons.beanutils.BeanUtilsBean;
import java.lang.reflect.InvocationTargetException;
public class MyBeansUtil extends BeanUtilsBean {
@Override
public void copyProperty(Object dest, String name, Object value)
throws IllegalAccessException, InvocationTargetException {
if(value == null) return;
super.copyProperty(dest, name, value);
}
}
...そしてここに私がいくつかの例でそれをテストしようとしている場所があります:
public class SandBox {
public static void main(String[] args) {
Person db = new Person("John", 36, new Pet("Lucy", 3));
Person db2 = new Person("John", 36, new Pet("Lucy", 2));
Person db3 = new Person("John", 36, new Pet("Lucy", 4));
Person in = new Person();
in.age = 17;
in.name = "Paul";
in.friend = new Pet(null, 35);
Person in2 = new Person();
in2.name = "Damian";
Person in3 = new Person();
in3.friend = new Pet("Lup", 25);
try {
BeanUtilsBean notNull =new MyBeansUtil();
notNull.copyProperties(db, in);
notNull.copyProperties(db2, in2);
notNull.copyProperties(db3, in3);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
残念ながら、元のオブジェクトdb、db1、db2は以前と同じままです。私はここで何か間違ったことをしていますか?
最終的にSpringBeanUtilsライブラリを使用しました。これが私の作業方法です:
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.lang.reflect.Field;
import java.util.Collection;
public class MyBeansUtil<T> {
public T copyNonNullProperties(T target, T in) {
if (in == null || target == null || target.getClass() != in.getClass()) return null;
final BeanWrapper src = new BeanWrapperImpl(in);
final BeanWrapper trg = new BeanWrapperImpl(target);
for (final Field property : target.getClass().getDeclaredFields()) {
Object providedObject = src.getPropertyValue(property.getName());
if (providedObject != null && !(providedObject instanceof Collection<?>)) {
trg.setPropertyValue(
property.getName(),
providedObject);
}
}
return target;
}
}
正常に動作しますが、コレクションであるフィールドを無視することに注意してください。それはわざとです、私はそれらを別々に扱います。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加