7

ブルドーザーのカスタムコンバーターをプログラムで設定するにはどうすればよいですか?次のコードは機能しません。

カスタムコンバータの実装:

class ConverterImpl extends DozerConverter<A, B> {

ConverterImpl() {
    super(A.class, B.class);
}

@Override
public B convertTo(A source, B destination) {
    return destination;
}

@Override
public A convertFrom(B source, A destination) {
    return destination;
}
}

テストコード:

DozerBeanMapper mapper = new DozerBeanMapper();
mapper.setCustomConverters(Collections.<CustomConverter>singletonList(new ConverterImpl()));
A a = new A(); 
B b = mapper.map(a, A.class);  

上記のコードを実行した後、カスタムコンバーターは呼び出されません。なにが問題ですか?

4

2 に答える 2

4

実際に特定のマッピングを追加する必要があるようですが、残念ながら、プログラム API を使用して指定できるのは、クラス レベルのコンバーターではなく、フィールド レベルのコンバーターのみです。したがって、A クラスと B クラスをコンテナー クラスでラップすると、A フィールドと B フィールドのマッピングを指定できます。

たとえば、次の冗長コードは期待どおりに機能します。

public class DozerMap {

   public static class ContainerA {
      private A a;
      public A getA() { return a; }
      public void setA(A a) { this.a = a; }
   }

   public static class ContainerB {
      private B b;
      public B getB() { return b; }
      public void setB(B b) { this.b = b; }
   }

   private static class A { };

   private static class B { };

   static class ConverterImpl extends DozerConverter<A, B> {

      ConverterImpl() {
         super(A.class, B.class);
      }

      @Override
      public B convertTo(A source, B destination) {
         Logger.getAnonymousLogger().info("Invoked");
         return destination;
      }

      @Override
      public A convertFrom(B source, A destination) {
         Logger.getAnonymousLogger().info("Invoked");
         return destination;
      }
   }

   public static void main(String[] args) {

      DozerBeanMapper mapper = new DozerBeanMapper();
      mapper.setCustomConverters(Collections.<CustomConverter> singletonList(new ConverterImpl()));
      BeanMappingBuilder foo = new BeanMappingBuilder() {

         @Override
         protected void configure() {
            mapping(ContainerA.class, ContainerB.class).fields("a", "b", FieldsMappingOptions.customConverter(ConverterImpl.class));
         }
      };
      mapper.setMappings(Collections.singletonList(foo));
      ContainerA containerA = new ContainerA();
      containerA.a = new A();
      ContainerB containerB = mapper.map(containerA, ContainerB.class);
   }
}
于 2012-05-14T10:08:41.110 に答える