1

アダプターを書き込もうとしています。あるクラスから別のクラスに適応させようとしているほぼ50の属性があります。

私のコードは次のようになります:

public static Type2 getType2(Type1 type1)
{
...

  if(!StringUtils.isEmpty(type1.getAttribute1()) {
     type2.setAttribute1( type1.getAttribute1() );
  }
  // and so on for all the 50 attributes
...
}

このアダプタメソッドを作成するためのより良い方法はありますか?

4

2 に答える 2

2

属性名が一致する場合は、ApacheCommonsBeanUtilsの使用を検討してください。

型変換が必要ない場合は、次を使用できますPropertyUtils.copyProperties()

public static Type2 getType2(Type1 type1) {
    Type2 type2 = new Type2();
    org.apache.commons.beanutils.PropertyUtils.copyProperties(type2, type1);
    return type2;
}

型変換が必要な場合は、BeanUtils.copyProperties()代わりに使用してください。

于 2012-12-18T10:49:12.567 に答える
2

あるインスタンスから別のインスタンスに属性をコピーするには、一般的な方法を使用できます。

public static <T> T copy(T source, T target) throws IllegalArgumentException, IllegalAccessException {
    for ( Field f : target.getClass().getDeclaredFields() ) {
        f.setAccessible( true );
        Object o = f.get( source );
        f.set( target, o);
    }
    return target;
}
于 2012-12-18T10:46:32.330 に答える