سؤال

هل هناك طريقة لتعيين حجم المجموعة في البلدوزر ؟

class Source {
    Collection<String> images;
}

class Destination {
  int numOfImages;
}
هل كانت مفيدة؟

المحلول

تحرير: لقد تحديث جوابي المخصصة لاستخدام محول على مستوى الميدان بدلا من مستوى الصف.

قد تكون هناك حلول أخرى سوى طريقة واحدة للقيام بذلك سيكون لاستخدام مخصص محول.لقد أضاف حاصل على واضعي إلى دروس و كتب ما يلي converter:

package com.mycompany.samples.dozer;

import java.util.Collection;

import org.dozer.DozerConverter;

public class TestCustomFieldConverter extends 
        DozerConverter<Collection, Integer> {

    public TestCustomFieldConverter() {
        super(Collection.class, Integer.class);
    }

    @Override
    public Integer convertTo(Collection source, Integer destination) {
        if (source != null) {
            return source.size();
        } else {
            return 0;
        }
    }

    @Override
    public Collection convertFrom(Integer source, Collection destination) {
        throw new IllegalStateException("Unknown value!");
    }
}

ثم يعلن في XML مخصصة ملف التعيين:

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://dozer.sourceforge.net
          http://dozer.sourceforge.net/schema/beanmapping.xsd">
  <mapping>
    <class-a>com.mycompany.samples.dozer.Source</class-a>
    <class-b>com.mycompany.samples.dozer.Destination</class-b>
    <field custom-converter="com.mycompany.samples.dozer.TestCustomFieldConverter">
      <a>images</a>
      <b>numOfImages</b>
    </field>
  </mapping>        
</mappings>

مع هذا الإعداد التالية اختبار يمر بنجاح:

@Test
public void testCollectionToIntMapping() {
    List<String> mappingFiles = new ArrayList<String>();
    mappingFiles.add("com/mycompany/samples/dozer/somedozermapping.xml");
    Mapper mapper = new DozerBeanMapper(mappingFiles);

    Source sourceObject = new Source();
    sourceObject.setImages(Arrays.asList( "a", "b", "C" ));

    Destination destObject = mapper.map(sourceObject, Destination.class);

    assertEquals(3, destObject.getNumOfImages());
}

نصائح أخرى

وهنا نهجا لحل هذه مع ModelMapper :

ModelMapper modelMapper = new ModelMapper();
modelMapper.createTypeMap(Source.class, Destination.class).setConverter(
    new AbstractConverter<Source, Destination>() {
      protected Destination convert(Source source) {
        Destination dest = new Destination();
        dest.numOfImages = source.images.size();
        return dest;
      }
    });

ويستخدم هذا المثال تحويل للطبقات المصدر والوجهة.

وعن الأمثلة ومستندات ويمكن الاطلاع على http://modelmapper.org

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top