基本的に別のクラスのコピーであるクラスがあります。
public class A {
int a;
String b;
}
public class CopyA {
int a;
String b;
}
私は何をやっていることは、クラスから値を入れているA
にCopyA
送信する前にCopyA
Webサービスを呼び出して。今、私は反射-メソッドを作成したいと思い、そのクラスから基本的にコピー(名前とタイプ別)同一であり、すべてのフィールドA
クラスへCopyA
。
これどうやってするの?
これは私がこれまでに持っているものですが、それは完全には機能しません。ここでの問題は、ループしているフィールドにフィールドを設定しようとしていることだと思います。
private <T extends Object, Y extends Object> void copyFields(T from, Y too) {
Class<? extends Object> fromClass = from.getClass();
Field[] fromFields = fromClass.getDeclaredFields();
Class<? extends Object> tooClass = too.getClass();
Field[] tooFields = tooClass.getDeclaredFields();
if (fromFields != null && tooFields != null) {
for (Field tooF : tooFields) {
logger.debug("toofield name #0 and type #1", tooF.getName(), tooF.getType().toString());
try {
// Check if that fields exists in the other method
Field fromF = fromClass.getDeclaredField(tooF.getName());
if (fromF.getType().equals(tooF.getType())) {
tooF.set(tooF, fromF);
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
すでにこれを何とかしてしている人がいるに違いない