Merge branch 'agudian_19'

# By Andreas Gudian (2) and Gunnar Morling (1)
* agudian_19:
  #19 Simplifying creation of MappingMethod objects
  #19 Map into existing instances. - Either defined explicitly with @MappingTarget, or implicitly as last parameter in a void method.
  Have spaces on empty for iterator pads
This commit is contained in:
Gunnar Morling 2013-07-21 11:41:49 +02:00
commit a931cff0e5
26 changed files with 638 additions and 199 deletions

View File

@ -108,7 +108,9 @@
<!-- Checks for whitespace -->
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
<module name="EmptyForIteratorPad"/>
<module name="EmptyForIteratorPad">
<property name="option" value="space" />
</module>
<module name="MethodParamPad"/>
<module name="NoWhitespaceAfter">
<property name="tokens" value="BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS, UNARY_PLUS"/>

View File

@ -0,0 +1,36 @@
/**
* Copyright 2012-2013 Gunnar Morling (http://www.gunnarmorling.de/)
* and/or other contributors as indicated by the @authors tag. See the
* copyright.txt file in the distribution for a full listing of all
* contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapstruct;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Declares a parameter of a mapping method to be the target of the mapping.
* <p>
* Not more than one parameter can be declared as {@code MappingTarget}.
* <p>
* For methods with return type {@code void}, the last parameter of the method is regarded as {@code MappingTarget},
* unless another parameter carries this annotation.
*
* @author Andreas Gudian
*/
@Target( ElementType.PARAMETER )
public @interface MappingTarget {
}

View File

@ -43,6 +43,7 @@ import org.mapstruct.IterableMapping;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.MappingTarget;
import org.mapstruct.Mappings;
import org.mapstruct.ap.model.Options;
import org.mapstruct.ap.model.ReportingPolicy;
@ -76,7 +77,8 @@ import org.mapstruct.ap.processor.ModelElementProcessor.ProcessorContext;
@GeneratePrism(value = Mapping.class, publicAccess = true),
@GeneratePrism(value = Mappings.class, publicAccess = true),
@GeneratePrism(value = IterableMapping.class, publicAccess = true),
@GeneratePrism(value = MapMapping.class, publicAccess = true)
@GeneratePrism(value = MapMapping.class, publicAccess = true),
@GeneratePrism(value = MappingTarget.class, publicAccess = true)
})
@SupportedOptions({
MappingProcessor.SUPPRESS_GENERATOR_TIMESTAMP,

View File

@ -21,6 +21,8 @@ package org.mapstruct.ap.model;
import java.util.List;
import java.util.Set;
import org.mapstruct.ap.model.source.Method;
/**
* A {@link MappingMethod} implemented by a {@link Mapper} class which maps one
* bean type to another, optionally configured by one or more
@ -32,9 +34,8 @@ public class BeanMappingMethod extends MappingMethod {
private final List<PropertyMapping> propertyMappings;
public BeanMappingMethod(String name, String parameterName, Type sourceType, Type targetType,
List<PropertyMapping> propertyMappings) {
super( name, parameterName, sourceType, targetType );
public BeanMappingMethod(Method method, List<PropertyMapping> propertyMappings) {
super( method );
this.propertyMappings = propertyMappings;
}

View File

@ -21,6 +21,7 @@ package org.mapstruct.ap.model;
import java.beans.Introspector;
import java.util.Set;
import org.mapstruct.ap.model.source.Method;
import org.mapstruct.ap.util.Strings;
/**
@ -34,9 +35,9 @@ public class IterableMappingMethod extends MappingMethod {
private final MappingMethodReference elementMappingMethod;
private final TypeConversion conversion;
public IterableMappingMethod(String name, String parameterName, Type sourceType, Type targetType,
MappingMethodReference elementMappingMethod, TypeConversion conversion) {
super( name, parameterName, sourceType, targetType );
public IterableMappingMethod(Method method, MappingMethodReference elementMappingMethod,
TypeConversion conversion) {
super( method );
this.elementMappingMethod = elementMappingMethod;
this.conversion = conversion;
}
@ -63,10 +64,11 @@ public class IterableMappingMethod extends MappingMethod {
public String getLoopVariableName() {
return Strings.getSaveVariableName(
Introspector.decapitalize(
getSourceType().getTypeParameters()
getSingleSourceParameter().getType()
.getTypeParameters()
.get( 0 )
.getName()
), getParameterName()
), getParameterNames()
);
}
}

View File

@ -20,6 +20,7 @@ package org.mapstruct.ap.model;
import java.util.Set;
import org.mapstruct.ap.model.source.Method;
import org.mapstruct.ap.util.Strings;
/**
@ -35,10 +36,9 @@ public class MapMappingMethod extends MappingMethod {
private final TypeConversion keyConversion;
private final TypeConversion valueConversion;
public MapMappingMethod(String name, String parameterName, Type sourceType, Type targetType,
MappingMethodReference keyMappingMethod, TypeConversion keyConversion,
public MapMappingMethod(Method method, MappingMethodReference keyMappingMethod, TypeConversion keyConversion,
MappingMethodReference valueMappingMethod, TypeConversion valueConversion) {
super( name, parameterName, sourceType, targetType );
super( method );
this.keyMappingMethod = keyMappingMethod;
this.keyConversion = keyConversion;
@ -74,21 +74,21 @@ public class MapMappingMethod extends MappingMethod {
public String getKeyVariableName() {
return Strings.getSaveVariableName(
"key",
getParameterName()
getParameterNames()
);
}
public String getValueVariableName() {
return Strings.getSaveVariableName(
"value",
getParameterName()
getParameterNames()
);
}
public String getEntryVariableName() {
return Strings.getSaveVariableName(
"entry",
getParameterName()
getParameterNames()
);
}
}

View File

@ -19,9 +19,13 @@
package org.mapstruct.ap.model;
import java.beans.Introspector;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.mapstruct.ap.model.source.Method;
import org.mapstruct.ap.model.source.Parameter;
import org.mapstruct.ap.util.Strings;
/**
@ -32,54 +36,73 @@ import org.mapstruct.ap.util.Strings;
public abstract class MappingMethod extends AbstractModelElement {
private final String name;
private final String parameterName;
private final Type sourceType;
private final Type targetType;
private final List<Parameter> parameters;
private final Type returnType;
private final Parameter singleSourceParameter;
private final Parameter targetParameter;
protected MappingMethod(String name, String parameterName, Type sourceType, Type targetType) {
this.name = name;
this.parameterName = parameterName;
this.sourceType = sourceType;
this.targetType = targetType;
public MappingMethod(Method method) {
this.name = method.getName();
this.parameters = method.getParameters();
this.returnType = method.getReturnType();
this.singleSourceParameter = method.getSingleSourceParameter();
this.targetParameter = method.getTargetParameter();
}
public String getName() {
return name;
}
public String getParameterName() {
return parameterName;
public List<Parameter> getParameters() {
return parameters;
}
public Type getSourceType() {
return sourceType;
public Parameter getSingleSourceParameter() {
return singleSourceParameter;
}
public Type getTargetType() {
return targetType;
public Type getResultType() {
return targetParameter != null ? targetParameter.getType() : returnType;
}
public String getResultName() {
return targetParameter != null ? targetParameter.getName() :
Strings.getSaveVariableName( Introspector.decapitalize( getResultType().getName() ), getParameterNames() );
}
public Type getReturnType() {
return returnType;
}
public boolean isExistingInstanceMapping() {
return targetParameter != null;
}
@Override
public Set<Type> getImportTypes() {
Set<Type> types = new HashSet<Type>();
types.add( getSourceType() );
types.add( getTargetType() );
for ( Parameter param : parameters ) {
types.add( param.getType() );
}
types.add( getReturnType() );
return types;
}
public String getReturnValueName() {
return Strings.getSaveVariableName(
Introspector.decapitalize( getTargetType().getName() ),
getParameterName()
);
protected List<String> getParameterNames() {
List<String> parameterNames = new ArrayList<String>( parameters.size() );
for ( Parameter parameter : parameters ) {
parameterNames.add( parameter.getName() );
}
return parameterNames;
}
@Override
public String toString() {
return "MappingMethod {" +
"\n name='" + name + "\'," +
"\n parameterName='" + parameterName + "\'," +
"\n}";
return returnType + " " + getName() + "(" + Strings.join( parameters, ", " ) + ")";
}
}

View File

@ -22,6 +22,7 @@ import java.beans.Introspector;
import java.util.HashSet;
import java.util.Set;
import org.mapstruct.ap.model.source.Method;
import org.mapstruct.ap.util.Strings;
/**
@ -33,10 +34,9 @@ public class MappingMethodReference extends MappingMethod {
private final Type declaringMapper;
public MappingMethodReference(Type declaringMapper, String name, String parameterName, Type sourceType,
Type targetType) {
super( name, parameterName, sourceType, targetType );
this.declaringMapper = declaringMapper;
public MappingMethodReference(Method method) {
super( method );
this.declaringMapper = method.getDeclaringMapper();
}
public Type getDeclaringMapper() {
@ -48,10 +48,6 @@ public class MappingMethodReference extends MappingMethod {
}
public Set<Type> getReferencedTypes() {
Set<Type> types = new HashSet<Type>();
types.add( getSourceType() );
types.add( getTargetType() );
return types;
return new HashSet<Type>();
}
}

View File

@ -22,7 +22,7 @@ package org.mapstruct.ap.model;
* The options passed to the code generator.
*
* @author Andreas Gudian
* @autor Gunnar Morling
* @author Gunnar Morling
*/
public class Options {
private final boolean suppressGeneratorTimestamp;

View File

@ -38,6 +38,10 @@ import org.mapstruct.ap.util.Strings;
* @author Gunnar Morling
*/
public class Type extends AbstractModelElement implements Comparable<Type> {
/**
* Type representing {@code void}
*/
public static final Type VOID = new Type( "void" );
private static final Set<String> PRIMITIVE_TYPE_NAMES = new HashSet<String>(
Arrays.asList( "boolean", "char", "byte", "short", "int", "long", "float", "double" )
@ -61,6 +65,7 @@ public class Type extends AbstractModelElement implements Comparable<Type> {
DEFAULT_MAP_IMPLEMENTATION_TYPES.put( Map.class.getName(), forClass( HashMap.class ) );
}
private final String canonicalName;
private final String packageName;
private final String name;
private final List<Type> typeParameters;
@ -77,6 +82,7 @@ public class Type extends AbstractModelElement implements Comparable<Type> {
if ( pakkage != null ) {
return new Type(
clazz.getCanonicalName(),
pakkage.getName(),
clazz.getSimpleName(),
clazz.isEnum(),
@ -92,15 +98,16 @@ public class Type extends AbstractModelElement implements Comparable<Type> {
}
public Type(String name) {
this( null, name, false, false, false, false, Collections.<Type>emptyList() );
this( name, null, name, false, false, false, false, Collections.<Type>emptyList() );
}
public Type(String packageName, String name) {
this( packageName, name, false, false, false, false, Collections.<Type>emptyList() );
this( packageName + "." + name, packageName, name, false, false, false, false, Collections.<Type>emptyList() );
}
public Type(String packageName, String name, boolean isEnumType, boolean isCollectionType,
public Type(String canonicalName, String packageName, String name, boolean isEnumType, boolean isCollectionType,
boolean isIterableType, boolean isMapType, List<Type> typeParameters) {
this.canonicalName = canonicalName;
this.packageName = packageName;
this.name = name;
this.isEnumType = isEnumType;
@ -126,6 +133,7 @@ public class Type extends AbstractModelElement implements Comparable<Type> {
if ( isMapType ) {
Type mapType = DEFAULT_MAP_IMPLEMENTATION_TYPES.get( packageName + "." + name );
mapImplementationType = mapType != null ? new Type(
mapType.getPackageName() + "." + mapType.getName(),
mapType.getPackageName(),
mapType.getName(),
mapType.isEnumType(),
@ -140,6 +148,10 @@ public class Type extends AbstractModelElement implements Comparable<Type> {
}
}
public String getCanonicalName() {
return canonicalName;
}
public String getPackageName() {
return packageName;
}

View File

@ -18,15 +18,19 @@
*/
package org.mapstruct.ap.model.source;
import java.beans.Introspector;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.ExecutableElement;
import org.mapstruct.ap.model.Type;
import org.mapstruct.ap.util.Strings;
/**
* Represents a mapping method with source and target type and the mappings
* between the properties of source and target type.
* Represents a mapping method with source and target type and the mappings between the properties of source and target
* type.
*
* @author Gunnar Morling
*/
@ -34,56 +38,78 @@ public class Method {
private final Type declaringMapper;
private final ExecutableElement executable;
private final String parameterName;
private final Type sourceType;
private final Type targetType;
private final List<Parameter> parameters;
private final Type returnType;
private Map<String, Mapping> mappings;
private IterableMapping iterableMapping;
private MapMapping mapMapping;
public static Method forMethodRequiringImplementation(ExecutableElement executable, String parameterName,
Type sourceType, Type targetType,
Map<String, Mapping> mappings,
private final Parameter singleSourceParameter;
private final Parameter targetParameter;
public static Method forMethodRequiringImplementation(ExecutableElement executable, List<Parameter> parameters,
Type returnType, Map<String, Mapping> mappings,
IterableMapping iterableMapping, MapMapping mapMapping) {
return new Method(
null,
executable,
parameterName,
sourceType,
targetType,
parameters,
returnType,
mappings,
iterableMapping,
mapMapping
);
}
public static Method forReferencedMethod(Type declaringMapper, ExecutableElement executable, String parameterName,
Type sourceType, Type targetType) {
public static Method forReferencedMethod(Type declaringMapper, ExecutableElement executable,
List<Parameter> parameters, Type returnType) {
return new Method(
declaringMapper,
executable,
parameterName,
sourceType,
targetType,
parameters,
returnType,
Collections.<String, Mapping>emptyMap(),
null,
null
);
}
private Method(Type declaringMapper, ExecutableElement executable, String parameterName, Type sourceType,
Type targetType, Map<String, Mapping> mappings, IterableMapping iterableMapping,
MapMapping mapMapping) {
private Method(Type declaringMapper, ExecutableElement executable, List<Parameter> parameters, Type returnType,
Map<String, Mapping> mappings, IterableMapping iterableMapping, MapMapping mapMapping) {
this.declaringMapper = declaringMapper;
this.executable = executable;
this.parameterName = parameterName;
this.sourceType = sourceType;
this.targetType = targetType;
this.parameters = parameters;
this.returnType = returnType;
this.mappings = mappings;
this.iterableMapping = iterableMapping;
this.mapMapping = mapMapping;
this.singleSourceParameter = determineSingleSourceParameter();
this.targetParameter = determineTargetParameter( parameters );
}
private Parameter determineTargetParameter(Iterable<Parameter> parameters) {
for ( Parameter parameter : parameters ) {
if ( parameter.isMappingTarget() ) {
return parameter;
}
}
return null;
}
private Parameter determineSingleSourceParameter() {
for ( Parameter parameter : parameters ) {
if ( !parameter.isMappingTarget() ) {
return parameter;
}
}
throw new IllegalStateException( "Method " + this + " has no source parameter." );
}
/**
@ -105,16 +131,31 @@ public class Method {
return executable.getSimpleName().toString();
}
public String getParameterName() {
return parameterName;
public List<Parameter> getParameters() {
return parameters;
}
public Type getSourceType() {
return sourceType;
public List<String> getParameterNames() {
List<String> parameterNames = new ArrayList<String>( parameters.size() );
for ( Parameter parameter : parameters ) {
parameterNames.add( parameter.getName() );
}
return parameterNames;
}
public Type getTargetType() {
return targetType;
public String getResultName() {
return targetParameter != null ? targetParameter.getName() :
Strings.getSaveVariableName( Introspector.decapitalize( getResultType().getName() ), getParameterNames() );
}
public Type getResultType() {
return targetParameter != null ? targetParameter.getType() : returnType;
}
public Type getReturnType() {
return returnType;
}
public Map<String, Mapping> getMappings() {
@ -143,16 +184,24 @@ public class Method {
public boolean reverses(Method method) {
return
equals( sourceType, method.getTargetType() ) &&
equals( targetType, method.getSourceType() );
equals( getSingleSourceParameter().getType(), method.getResultType() )
&& equals( getResultType(), method.getSingleSourceParameter().getType() );
}
public Parameter getSingleSourceParameter() {
return singleSourceParameter;
}
public Parameter getTargetParameter() {
return targetParameter;
}
public boolean isIterableMapping() {
return sourceType.isIterableType() && targetType.isIterableType();
return getSingleSourceParameter().getType().isIterableType() && getResultType().isIterableType();
}
public boolean isMapMapping() {
return sourceType.isMapType() && targetType.isMapType();
return getSingleSourceParameter().getType().isMapType() && getResultType().isMapType();
}
private boolean equals(Object o1, Object o2) {
@ -161,6 +210,6 @@ public class Method {
@Override
public String toString() {
return targetType + " " + getName() + "(" + sourceType + " " + parameterName + ")";
return returnType + " " + getName() + "(" + Strings.join( parameters, ", " ) + ")";
}
}

View File

@ -29,10 +29,16 @@ public class Parameter {
private final String name;
private final Type type;
private final boolean mappingTarget;
public Parameter(String name, Type type) {
public Parameter(String name, Type type, boolean mappingTarget) {
this.name = name;
this.type = type;
this.mappingTarget = mappingTarget;
}
public Parameter(String name, Type type) {
this( name, type, false );
}
public String getName() {
@ -43,8 +49,12 @@ public class Parameter {
return type;
}
public boolean isMappingTarget() {
return mappingTarget;
}
@Override
public String toString() {
return type.toString() + " " + name;
return ( mappingTarget ? "@MappingTarget " : "" ) + type.toString() + " " + name;
}
}

View File

@ -54,6 +54,7 @@ import org.mapstruct.ap.model.Type;
import org.mapstruct.ap.model.TypeConversion;
import org.mapstruct.ap.model.source.Mapping;
import org.mapstruct.ap.model.source.Method;
import org.mapstruct.ap.model.source.Parameter;
import org.mapstruct.ap.util.Executables;
import org.mapstruct.ap.util.Filters;
import org.mapstruct.ap.util.Strings;
@ -200,19 +201,18 @@ public class MapperCreationProcessor implements ModelElementProcessor<List<Metho
Map<String, Mapping> mappings = method.getMappings();
TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getExecutable().getReturnType() );
TypeElement parameterElement = (TypeElement) typeUtils.asElement(
method.getExecutable()
.getParameters()
.get( 0 )
.asType()
TypeElement resultTypeElement = elementUtils.getTypeElement( method.getResultType().getCanonicalName() );
TypeElement parameterElement = elementUtils.getTypeElement(
method.getSingleSourceParameter()
.getType()
.getCanonicalName()
);
List<ExecutableElement> sourceGetters = Filters.getterMethodsIn(
elementUtils.getAllMembers( parameterElement )
);
List<ExecutableElement> targetSetters = Filters.setterMethodsIn(
elementUtils.getAllMembers( returnTypeElement )
elementUtils.getAllMembers( resultTypeElement )
);
Set<String> sourceProperties = executables.getPropertyNames(
@ -255,13 +255,7 @@ public class MapperCreationProcessor implements ModelElementProcessor<List<Metho
mappedTargetProperties
);
return new BeanMappingMethod(
method.getName(),
method.getParameterName(),
method.getSourceType(),
method.getTargetType(),
propertyMappings
);
return new BeanMappingMethod( method, propertyMappings );
}
private void reportErrorForUnmappedTargetPropertiesIfRequired(Method method,
@ -302,7 +296,7 @@ public class MapperCreationProcessor implements ModelElementProcessor<List<Metho
String.format(
"Unknown property \"%s\" in parameter type %s.",
mappedProperty.getSourceName(),
method.getSourceType()
method.getSingleSourceParameter().getType()
),
method.getExecutable(),
mappedProperty.getMirror(),
@ -315,7 +309,7 @@ public class MapperCreationProcessor implements ModelElementProcessor<List<Metho
String.format(
"Unknown property \"%s\" in return type %s.",
mappedProperty.getTargetName(),
method.getTargetType()
method.getResultType()
),
method.getExecutable(),
mappedProperty.getMirror(),
@ -328,22 +322,20 @@ public class MapperCreationProcessor implements ModelElementProcessor<List<Metho
private PropertyMapping getPropertyMapping(List<Method> methods, Method method, ExecutableElement getterMethod,
ExecutableElement setterMethod, String dateFormat) {
Type sourceType = executables.retrieveReturnType( getterMethod );
Type targetType = executables.retrieveParameter( setterMethod ).getType();
Type targetType = executables.retrieveSingleParameter( setterMethod ).getType();
MappingMethodReference propertyMappingMethod = getMappingMethodReference( methods, sourceType, targetType );
TypeConversion conversion = getConversion(
sourceType,
targetType,
dateFormat,
method.getParameterName() + "." + getterMethod.getSimpleName().toString() + "()"
method.getSingleSourceParameter().getName() + "."
+ getterMethod.getSimpleName().toString() + "()"
);
PropertyMapping property = new PropertyMapping(
method.getParameterName(),
Strings.getSaveVariableName(
Introspector.decapitalize( method.getTargetType().getName() ),
method.getParameterName()
),
method.getSingleSourceParameter().getName(),
method.getResultName(),
executables.getPropertyName( getterMethod ),
getterMethod.getSimpleName().toString(),
sourceType,
@ -363,8 +355,8 @@ public class MapperCreationProcessor implements ModelElementProcessor<List<Metho
}
private MappingMethod getIterableMappingMethod(List<Method> methods, Method method) {
Type sourceElementType = method.getSourceType().getTypeParameters().get( 0 );
Type targetElementType = method.getTargetType().getTypeParameters().get( 0 );
Type sourceElementType = method.getSingleSourceParameter().getType().getTypeParameters().get( 0 );
Type targetElementType = method.getResultType().getTypeParameters().get( 0 );
TypeConversion conversion = getConversion(
sourceElementType,
@ -372,25 +364,25 @@ public class MapperCreationProcessor implements ModelElementProcessor<List<Metho
method.getIterableMapping() != null ? method.getIterableMapping().getDateFormat() : null,
Strings.getSaveVariableName(
Introspector.decapitalize( sourceElementType.getName() ),
method.getParameterName()
method.getParameterNames()
)
);
return new IterableMappingMethod(
method.getName(),
method.getParameterName(),
method.getSourceType(),
method.getTargetType(),
method,
getMappingMethodReference( methods, sourceElementType, targetElementType ),
conversion
);
}
private MappingMethod getMapMappingMethod(List<Method> methods, Method method) {
Type sourceKeyType = method.getSourceType().getTypeParameters().get( 0 );
Type sourceValueType = method.getSourceType().getTypeParameters().get( 1 );
Type targetKeyType = method.getTargetType().getTypeParameters().get( 0 );
Type targetValueType = method.getTargetType().getTypeParameters().get( 1 );
List<Type> sourceTypeParams = method.getSingleSourceParameter().getType().getTypeParameters();
Type sourceKeyType = sourceTypeParams.get( 0 );
Type sourceValueType = sourceTypeParams.get( 1 );
List<Type> resultTypeParams = method.getResultType().getTypeParameters();
Type targetKeyType = resultTypeParams.get( 0 );
Type targetValueType = resultTypeParams.get( 1 );
String keyDateFormat = method.getMapMapping() != null ? method.getMapMapping().getKeyFormat() : null;
String valueDateFormat = method.getMapMapping() != null ? method.getMapMapping().getValueFormat() : null;
@ -410,16 +402,7 @@ public class MapperCreationProcessor implements ModelElementProcessor<List<Metho
targetValueType
);
return new MapMappingMethod(
method.getName(),
method.getParameterName(),
method.getSourceType(),
method.getTargetType(),
keyMappingMethod,
keyConversion,
valueMappingMethod,
valueConversion
);
return new MapMappingMethod( method, keyMappingMethod, keyConversion, valueMappingMethod, valueConversion );
}
private TypeConversion getConversion(Type sourceType, Type targetType, String dateFormat, String sourceReference) {
@ -435,14 +418,11 @@ public class MapperCreationProcessor implements ModelElementProcessor<List<Metho
private MappingMethodReference getMappingMethodReference(Iterable<Method> methods, Type parameterType,
Type returnType) {
for ( Method oneMethod : methods ) {
if ( oneMethod.getSourceType().equals( parameterType ) && oneMethod.getTargetType().equals( returnType ) ) {
return new MappingMethodReference(
oneMethod.getDeclaringMapper(),
oneMethod.getName(),
oneMethod.getParameterName(),
oneMethod.getSourceType(),
oneMethod.getTargetType()
);
Parameter singleSourceParam = oneMethod.getSingleSourceParameter();
if ( singleSourceParam.getType().equals( parameterType ) &&
oneMethod.getResultType().equals( returnType ) ) {
return new MappingMethodReference( oneMethod );
}
}

View File

@ -115,19 +115,23 @@ public class MethodRetrievalProcessor implements ModelElementProcessor<Void, Lis
}
private Method getMethod(TypeElement element, ExecutableElement method, boolean implementationRequired) {
Parameter parameter = executables.retrieveParameter( method );
List<Parameter> parameters = executables.retrieveParameters( method );
Type returnType = executables.retrieveReturnType( method );
//add method with property mappings if an implementation needs to be generated
if ( implementationRequired ) {
boolean isValid = checkParameterAndReturnType( method, parameter.getType(), returnType );
List<Parameter> sourceParameters = extractSourceParameters( parameters );
Parameter targetParameter = extractTargetParameter( parameters );
Type resultType = selectResultType( returnType, targetParameter );
boolean isValid =
checkParameterAndReturnType( method, sourceParameters, targetParameter, resultType, returnType );
if ( isValid ) {
return
Method.forMethodRequiringImplementation(
method,
parameter.getName(),
parameter.getType(),
parameters,
returnType,
getMappings( method ),
IterableMapping.fromPrism( IterableMappingPrism.getInstanceOn( method ) ),
@ -139,20 +143,92 @@ public class MethodRetrievalProcessor implements ModelElementProcessor<Void, Lis
}
}
//otherwise add reference to existing mapper method
else {
else if ( parameters.size() == 1 ) {
return
Method.forReferencedMethod(
typeUtil.getType( typeUtils.getDeclaredType( element ) ),
method,
parameter.getName(),
parameter.getType(),
parameters,
returnType
);
}
else {
return null;
}
}
private boolean checkParameterAndReturnType(ExecutableElement method, Type parameterType, Type returnType) {
if ( parameterType.isIterableType() && !returnType.isIterableType() ) {
private Parameter extractTargetParameter(List<Parameter> parameters) {
for ( Parameter param : parameters ) {
if ( param.isMappingTarget() ) {
return param;
}
}
return null;
}
private List<Parameter> extractSourceParameters(List<Parameter> parameters) {
List<Parameter> sourceParameters = new ArrayList<Parameter>( parameters.size() );
for ( Parameter param : parameters ) {
if ( !param.isMappingTarget() ) {
sourceParameters.add( param );
}
}
return sourceParameters;
}
private Type selectResultType(Type returnType, Parameter targetParameter) {
if ( null != targetParameter ) {
return targetParameter.getType();
}
else {
return returnType;
}
}
private boolean checkParameterAndReturnType(ExecutableElement method, List<Parameter> sourceParameters,
Parameter targetParameter, Type resultType, Type returnType) {
if ( sourceParameters.isEmpty() ) {
messager.printMessage( Kind.ERROR, "Can't generate mapping method with no input arguments.", method );
return false;
}
if ( sourceParameters.size() > 1 ) {
messager.printMessage(
Kind.ERROR,
"Mappings from more than one source objects are not yet supported.",
method
);
return false;
}
if ( targetParameter != null && ( sourceParameters.size() + 1 != method.getParameters().size() ) ) {
messager.printMessage(
Kind.ERROR,
"Can't generate mapping method with more than one @MappingTarget parameter.",
method
);
return false;
}
if ( resultType == Type.VOID ) {
messager.printMessage( Kind.ERROR, "Can't generate mapping method with return type void.", method );
return false;
}
if ( returnType != Type.VOID && !typeUtil.isAssignable( resultType, returnType ) ) {
messager.printMessage(
Kind.ERROR,
"The result type is not assignable to the the return type.",
method
);
return false;
}
Type parameterType = sourceParameters.get( 0 ).getType();
if ( parameterType.isIterableType() && !resultType.isIterableType() ) {
messager.printMessage(
Kind.ERROR,
"Can't generate mapping method from iterable type to non-iterable type.",
@ -161,7 +237,7 @@ public class MethodRetrievalProcessor implements ModelElementProcessor<Void, Lis
return false;
}
if ( !parameterType.isIterableType() && returnType.isIterableType() ) {
if ( !parameterType.isIterableType() && resultType.isIterableType() ) {
messager.printMessage(
Kind.ERROR,
"Can't generate mapping method from non-iterable type to iterable type.",
@ -175,7 +251,7 @@ public class MethodRetrievalProcessor implements ModelElementProcessor<Void, Lis
return false;
}
if ( returnType.isPrimitive() ) {
if ( resultType.isPrimitive() ) {
messager.printMessage( Kind.ERROR, "Can't generate mapping method with primitive return type.", method );
return false;
}

View File

@ -19,13 +19,16 @@
package org.mapstruct.ap.util;
import java.beans.Introspector;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import org.mapstruct.ap.MappingTargetPrism;
import org.mapstruct.ap.model.Type;
import org.mapstruct.ap.model.source.Parameter;
@ -105,7 +108,7 @@ public class Executables {
return propertyNames;
}
public Parameter retrieveParameter(ExecutableElement method) {
public Parameter retrieveSingleParameter(ExecutableElement method) {
List<? extends VariableElement> parameters = method.getParameters();
if ( parameters.size() != 1 ) {
@ -117,10 +120,42 @@ public class Executables {
return new Parameter(
parameter.getSimpleName().toString(),
typeUtil.retrieveType( parameter.asType() )
typeUtil.retrieveType( parameter.asType() ),
false
);
}
public List<Parameter> retrieveParameters(ExecutableElement method) {
List<? extends VariableElement> parameters = method.getParameters();
List<Parameter> result = new ArrayList<Parameter>( parameters.size() );
boolean mappingTargetDefined = false;
for ( Iterator<? extends VariableElement> it = parameters.iterator(); it.hasNext(); ) {
VariableElement parameter = it.next();
boolean isExplicitMappingTarget = null != MappingTargetPrism.getInstanceOn( parameter );
mappingTargetDefined |= isExplicitMappingTarget;
result
.add(
new Parameter(
parameter.getSimpleName().toString(),
typeUtil.retrieveType( parameter.asType() ),
// the parameter is a mapping target, if it was either defined explicitly or if if this is the
// last parameter in a multi-argument void method
isExplicitMappingTarget
|| ( !mappingTargetDefined && isMultiArgVoidMethod( method ) && !it.hasNext() )
)
);
}
return result;
}
public boolean isMultiArgVoidMethod(ExecutableElement method) {
return method.getParameters().size() > 1 && Type.VOID == retrieveReturnType( method );
}
public Type retrieveReturnType(ExecutableElement method) {
return typeUtil.retrieveType( method.getReturnType() );
}

View File

@ -19,6 +19,7 @@
package org.mapstruct.ap.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
@ -114,8 +115,12 @@ public class Strings {
}
public static String getSaveVariableName(String name, String... existingVariableNames) {
return getSaveVariableName( name, Arrays.asList( existingVariableNames ) );
}
public static String getSaveVariableName(String name, Collection<String> existingVariableNames) {
Set<String> conflictingNames = new HashSet<String>( KEYWORDS );
conflictingNames.addAll( Arrays.asList( existingVariableNames ) );
conflictingNames.addAll( existingVariableNames );
while ( conflictingNames.contains( name ) ) {
name = name + "_";

View File

@ -23,6 +23,7 @@ import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
@ -56,6 +57,7 @@ public class TypeUtil {
}
return new Type(
( (TypeElement) type.asElement() ).getQualifiedName().toString(),
elementUtils.getPackageOf( type.asElement() ).toString(),
type.asElement().getSimpleName().toString(),
type.asElement().getKind() == ElementKind.ENUM,
@ -85,8 +87,42 @@ public class TypeUtil {
else if ( mirror.getKind() == TypeKind.DECLARED ) {
return getType( ( (DeclaredType) mirror ) );
}
else if ( mirror.getKind() == TypeKind.VOID ) {
return Type.VOID;
}
else {
return new Type( mirror.toString() );
}
}
/**
* @param type1 first type
* @param type2 second type
*
* @return {@code true} if and only if the first type is assignable to the second
*/
public boolean isAssignable(Type type1, Type type2) {
if ( type1.equals( type2 ) ) {
return true;
}
TypeMirror mirror1 = toTypeMirror( type1 );
TypeMirror mirror2 = toTypeMirror( type2 );
return null != mirror1 && null != mirror2 && typeUtils.isAssignable( mirror1, mirror2 );
}
private TypeMirror toTypeMirror(Type type) {
TypeElement rawType = elementUtils.getTypeElement( type.getCanonicalName() );
if ( null == rawType ) {
return null;
}
TypeMirror[] parameters = new TypeMirror[type.getTypeParameters().size()];
for ( int i = 0; i < type.getTypeParameters().size(); i++ ) {
parameters[i] = toTypeMirror( type.getTypeParameters().get( i ) );
}
return typeUtils.getDeclaredType( rawType, parameters );
}
}

View File

@ -19,16 +19,20 @@
-->
@Override
public ${targetType.name} ${name}(${sourceType.name} ${parameterName}) {
if ( ${parameterName} == null ) {
return null;
public ${returnType.name} ${name}(<#list parameters as param>${param.type.name} ${param.name}<#if param_has_next>, </#if></#list>) {
if ( ${singleSourceParameter.name} == null ) {
return<#if returnType.name != "void"> null</#if>;
}
${targetType.name} ${returnValueName} = new ${targetType.name}();
<#if !existingInstanceMapping>
${resultType.name} ${resultName} = new ${resultType.name}();
</#if>
<#list propertyMappings as propertyMapping>
<@includeModel object=propertyMapping/>
</#list>
<#if returnType.name != "void">
return ${returnValueName};
return ${resultName};
</#if>
}

View File

@ -19,23 +19,27 @@
-->
@Override
public <@includeModel object=targetType/> ${name}(<@includeModel object=sourceType/> ${parameterName}) {
if ( ${parameterName} == null ) {
return null;
public <@includeModel object=returnType/> ${name}(<#list parameters as param><@includeModel object=param.type/> ${param.name}<#if param_has_next>, </#if></#list>) {
if ( ${singleSourceParameter.name} == null ) {
return<#if returnType.name != "void"> null</#if>;
}
<#if existingInstanceMapping>
${resultName}.clear();
<#else>
<#-- Use the interface type on the left side, except it is java.lang.Iterable; use the implementation type - if present - on the right side -->
<#if targetType.name == "Iterable" && targetType.packageName == "java.lang">${targetType.iterableImplementationType.name}<#else>${targetType.name}</#if><<@includeModel object=targetType.typeParameters[0]/>> ${returnValueName} = new <#if targetType.iterableImplementationType??>${targetType.iterableImplementationType.name}<#else>${targetType.name}</#if><<@includeModel object=targetType.typeParameters[0]/>>();
<#if resultType.name == "Iterable" && resultType.packageName == "java.lang">${resultType.iterableImplementationType.name}<#else>${resultType.name}</#if><<@includeModel object=resultType.typeParameters[0]/>> ${resultName} = new <#if resultType.iterableImplementationType??>${resultType.iterableImplementationType.name}<#else>${resultType.name}</#if><<@includeModel object=resultType.typeParameters[0]/>>();
</#if>
for ( <@includeModel object=sourceType.typeParameters[0]/> ${loopVariableName} : ${parameterName} ) {
for ( <@includeModel object=singleSourceParameter.type.typeParameters[0]/> ${loopVariableName} : ${singleSourceParameter.name} ) {
<#if elementMappingMethod??>
${returnValueName}.add( <@includeModel object=elementMappingMethod input="${loopVariableName}"/> );
${resultName}.add( <@includeModel object=elementMappingMethod input="${loopVariableName}"/> );
<#else>
<#if (conversion.exceptionTypes?size == 0) >
${returnValueName}.add( <@includeModel object=conversion/> );
${resultName}.add( <@includeModel object=conversion/> );
<#else>
try {
${returnValueName}.add( <@includeModel object=conversion/> );
${resultName}.add( <@includeModel object=conversion/> );
}
<#list conversion.exceptionTypes as exceptionType>
catch( ${exceptionType.name} e ) {
@ -45,6 +49,8 @@
</#if>
</#if>
}
<#if returnType.name != "void">
return ${returnValueName};
return ${resultName};
</#if>
}

View File

@ -19,23 +19,27 @@
-->
@Override
public <@includeModel object=targetType /> ${name}(<@includeModel object=sourceType /> ${parameterName}) {
if ( ${parameterName} == null ) {
return null;
public <@includeModel object=returnType /> ${name}(<#list parameters as param><@includeModel object=param.type/> ${param.name}<#if param_has_next>, </#if></#list>) {
if ( ${singleSourceParameter.name} == null ) {
return<#if returnType.name != "void"> null</#if>;
}
<@includeModel object=targetType /> ${returnValueName} = new <#if targetType.mapImplementationType??><@includeModel object=targetType.mapImplementationType /><#else><@includeModel object=targetType /></#if>();
<#if existingInstanceMapping>
${resultName}.clear();
<#else>
<@includeModel object=resultType /> ${resultName} = new <#if resultType.mapImplementationType??><@includeModel object=resultType.mapImplementationType /><#else><@includeModel object=resultType /></#if>();
</#if>
for ( Map.Entry<<#list sourceType.typeParameters as typeParameter><@includeModel object=typeParameter /><#if typeParameter_has_next>, </#if></#list>> ${entryVariableName} : ${parameterName}.entrySet() ) {
for ( Map.Entry<<#list singleSourceParameter.type.typeParameters as typeParameter><@includeModel object=typeParameter /><#if typeParameter_has_next>, </#if></#list>> ${entryVariableName} : ${singleSourceParameter.name}.entrySet() ) {
<#-- key -->
<#if keyMappingMethod??>
<@includeModel object=targetType.typeParameters[0]/> ${keyVariableName} = <@includeModel object=keyMappingMethod input="entry.getKey()"/>;
<@includeModel object=resultType.typeParameters[0]/> ${keyVariableName} = <@includeModel object=keyMappingMethod input="entry.getKey()"/>;
<#elseif keyConversion??>
<#if (keyConversion.exceptionTypes?size == 0) >
<@includeModel object=targetType.typeParameters[0]/> ${keyVariableName} = <@includeModel object=keyConversion/>;
<@includeModel object=resultType.typeParameters[0]/> ${keyVariableName} = <@includeModel object=keyConversion/>;
<#else>
<@includeModel object=targetType.typeParameters[0]/> ${keyVariableName};
<@includeModel object=resultType.typeParameters[0]/> ${keyVariableName};
try {
${keyVariableName} = <@includeModel object=keyConversion/>;
}
@ -46,16 +50,16 @@
</#list>
</#if>
<#else>
<@includeModel object=targetType.typeParameters[0]/> ${keyVariableName} = entry.getKey();
<@includeModel object=resultType.typeParameters[0]/> ${keyVariableName} = entry.getKey();
</#if>
<#-- value -->
<#if valueMappingMethod??>
<@includeModel object=targetType.typeParameters[1]/> ${valueVariableName} = <@includeModel object=valueMappingMethod input="entry.getValue()"/>;
<@includeModel object=resultType.typeParameters[1]/> ${valueVariableName} = <@includeModel object=valueMappingMethod input="entry.getValue()"/>;
<#elseif valueConversion??>
<#if (valueConversion.exceptionTypes?size == 0) >
<@includeModel object=targetType.typeParameters[1]/> ${valueVariableName} = <@includeModel object=valueConversion/>;
<@includeModel object=resultType.typeParameters[1]/> ${valueVariableName} = <@includeModel object=valueConversion/>;
<#else>
<@includeModel object=targetType.typeParameters[1]/> ${valueVariableName};
<@includeModel object=resultType.typeParameters[1]/> ${valueVariableName};
try {
${valueVariableName} = <@includeModel object=valueConversion/>;
}
@ -66,11 +70,13 @@
</#list>
</#if>
<#else>
<@includeModel object=targetType.typeParameters[1]/> ${valueVariableName} = entry.getValue();
<@includeModel object=resultType.typeParameters[1]/> ${valueVariableName} = entry.getValue();
</#if>
${returnValueName}.put( ${keyVariableName}, ${valueVariableName} );
${resultName}.put( ${keyVariableName}, ${valueVariableName} );
}
<#if returnType.name != "void">
return ${returnValueName};
return ${resultName};
</#if>
}

View File

@ -18,8 +18,10 @@
*/
package org.mapstruct.ap.test.collection.defaultimplementation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.mapstruct.ap.testutil.IssueKey;
import org.mapstruct.ap.testutil.MapperTestBase;
@ -41,7 +43,7 @@ public class DefaultCollectionImplementationTest extends MapperTestBase {
@IssueKey("6")
public void shouldUseDefaultImplementationForList() {
Source source = new Source();
source.setFooList( Arrays.asList( new SourceFoo( "Bob" ), new SourceFoo( "Alice" ) ) );
source.setFooList( createSourceFooList() );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
@ -52,7 +54,7 @@ public class DefaultCollectionImplementationTest extends MapperTestBase {
@IssueKey("6")
public void shouldUseDefaultImplementationForSet() {
Source source = new Source();
source.setFooSet( new HashSet<SourceFoo>( Arrays.asList( new SourceFoo( "Bob" ), new SourceFoo( "Alice" ) ) ) );
source.setFooSet( new HashSet<SourceFoo>( createSourceFooList() ) );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
@ -63,7 +65,7 @@ public class DefaultCollectionImplementationTest extends MapperTestBase {
@IssueKey("6")
public void shouldUseDefaultImplementationForCollection() {
Source source = new Source();
source.setFooCollection( Arrays.asList( new SourceFoo( "Bob" ), new SourceFoo( "Alice" ) ) );
source.setFooCollection( createSourceFooList() );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
@ -74,10 +76,49 @@ public class DefaultCollectionImplementationTest extends MapperTestBase {
@IssueKey("6")
public void shouldUseDefaultImplementationForIterable() {
Source source = new Source();
source.setFooIterable( Arrays.asList( new SourceFoo( "Bob" ), new SourceFoo( "Alice" ) ) );
source.setFooIterable( createSourceFooList() );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getFooIterable() ).containsOnly( new TargetFoo( "Bob" ), new TargetFoo( "Alice" ) );
Iterable<TargetFoo> fooIterable = target.getFooIterable();
assertResultList( fooIterable );
}
private void assertResultList(Iterable<TargetFoo> fooIterable) {
assertThat( fooIterable ).isNotNull();
assertThat( fooIterable ).containsOnly( new TargetFoo( "Bob" ), new TargetFoo( "Alice" ) );
}
private List<SourceFoo> createSourceFooList() {
return Arrays.asList( new SourceFoo( "Bob" ), new SourceFoo( "Alice" ) );
}
@Test
@IssueKey("19")
public void existingMapping1() {
List<TargetFoo> target = new ArrayList<TargetFoo>();
SourceTargetMapper.INSTANCE.sourceFoosToTargetFoos1( createSourceFooList(), target );
assertResultList( target );
}
@Test
@IssueKey("19")
public void existingMapping2() {
List<TargetFoo> target = new ArrayList<TargetFoo>();
SourceTargetMapper.INSTANCE.sourceFoosToTargetFoos2( target, createSourceFooList() );
assertResultList( target );
}
@Test
@IssueKey("19")
public void existingMapping3() {
List<TargetFoo> target = new ArrayList<TargetFoo>();
Iterable<TargetFoo> result =
SourceTargetMapper.INSTANCE.sourceFoosToTargetFoos3( createSourceFooList(), target );
assertThat( target == result ).isTrue();
assertResultList( target );
}
}

View File

@ -24,6 +24,7 @@ import java.util.Set;
import org.mapstruct.Mapper;
import org.mapstruct.Mappers;
import org.mapstruct.MappingTarget;
@Mapper
public interface SourceTargetMapper {
@ -41,4 +42,11 @@ public interface SourceTargetMapper {
Collection<TargetFoo> sourceFoosToTargetFoos(Collection<SourceFoo> foos);
Iterable<TargetFoo> sourceFoosToTargetFoos(Iterable<SourceFoo> foos);
void sourceFoosToTargetFoos1(Iterable<SourceFoo> sourceFoos, List<TargetFoo> targetFoos);
void sourceFoosToTargetFoos2(@MappingTarget List<TargetFoo> targetFoos, Iterable<SourceFoo> sourceFoos);
Iterable<TargetFoo> sourceFoosToTargetFoos3(Iterable<SourceFoo> sourceFoos,
@MappingTarget List<TargetFoo> targetFoos);
}

View File

@ -58,12 +58,55 @@ public class MapMappingTest extends MapperTestBase {
@Test
public void shouldCreateReverseMapMethodImplementation() {
Map<String, String> values = new HashMap<String, String>();
values.put( "42", "01.01.1980" );
values.put( "121", "20.07.2013" );
Map<String, String> values = createStringStringMap();
Map<Long, Date> target = SourceTargetMapper.INSTANCE.stringStringMapToLongDateMap( values );
assertResult( target );
}
@Test
@IssueKey("19")
public void shouldCreateReverseMapMethodImplementation1() {
Map<String, String> values = createStringStringMap();
Map<Long, Date> target = new HashMap<Long, Date>();
target.put( 66L, new GregorianCalendar( 2013, 7, 16 ).getTime() );
SourceTargetMapper.INSTANCE.stringStringMapToLongDateMap( values, target );
assertResult( target );
}
@Test
@IssueKey("19")
public void shouldCreateReverseMapMethodImplementation2() {
Map<String, String> values = createStringStringMap();
Map<Long, Date> target = new HashMap<Long, Date>();
target.put( 66L, new GregorianCalendar( 2013, 7, 16 ).getTime() );
SourceTargetMapper.INSTANCE.stringStringMapToLongDateMap2( target, values );
assertResult( target );
}
@Test
@IssueKey("19")
public void shouldCreateReverseMapMethodImplementation3() {
Map<String, String> values = createStringStringMap();
Map<Long, Date> target = new HashMap<Long, Date>();
target.put( 66L, new GregorianCalendar( 2013, 7, 16 ).getTime() );
Map<Long, Date> returnedTarget = SourceTargetMapper.INSTANCE.stringStringMapToLongDateMap3( values, target );
assertThat( target ).isSameAs( returnedTarget );
assertResult( target );
}
private void assertResult(Map<Long, Date> target) {
assertThat( target ).isNotNull();
assertThat( target ).hasSize( 2 );
assertThat( target ).includes(
@ -72,6 +115,13 @@ public class MapMappingTest extends MapperTestBase {
);
}
private Map<String, String> createStringStringMap() {
Map<String, String> values = new HashMap<String, String>();
values.put( "42", "01.01.1980" );
values.put( "121", "20.07.2013" );
return values;
}
@Test
public void shouldInvokeMapMethodImplementationForMapTypedProperty() {
Map<Long, Date> values = new HashMap<Long, Date>();
@ -94,9 +144,7 @@ public class MapMappingTest extends MapperTestBase {
@Test
public void shouldInvokeReverseMapMethodImplementationForMapTypedProperty() {
Map<String, String> values = new HashMap<String, String>();
values.put( "42", "01.01.1980" );
values.put( "121", "20.07.2013" );
Map<String, String> values = createStringStringMap();
Target target = new Target();
target.setValues( values );

View File

@ -24,17 +24,27 @@ import java.util.Map;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.Mappers;
import org.mapstruct.MappingTarget;
@Mapper(uses = CustomNumberMapper.class)
public interface SourceTargetMapper {
SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
@MapMapping( valueDateFormat = "dd.MM.yyyy" )
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> longDateMapToStringStringMap(Map<Long, Date> source);
Map<Long, Date> stringStringMapToLongDateMap(Map<String, String> source);
@MapMapping(valueDateFormat = "dd.MM.yyyy")
void stringStringMapToLongDateMap(Map<String, String> source, Map<Long, Date> target);
@MapMapping(valueDateFormat = "dd.MM.yyyy")
void stringStringMapToLongDateMap2(@MappingTarget Map<Long, Date> target, Map<String, String> source);
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<Long, Date> stringStringMapToLongDateMap3(Map<String, String> source, @MappingTarget Map<Long, Date> target);
Target sourceToTarget(Source source);
Source targetToSource(Target target);

View File

@ -36,17 +36,61 @@ public class InheritanceTest extends MapperTestBase {
@Test
@IssueKey("17")
public void shouldMapAttributeFromSuperType() {
SourceExt source = new SourceExt();
source.setFoo( 42 );
source.setBar( 23L );
SourceExt source = createSource();
TargetExt target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertResult( target );
}
@Test
@IssueKey("19")
public void existingMapping1() {
SourceExt source = createSource();
TargetExt target = new TargetExt();
SourceTargetMapper.INSTANCE.sourceToTarget1( source, target );
assertResult( target );
}
@Test
@IssueKey("19")
public void existingMapping2() {
SourceExt source = createSource();
TargetExt target = new TargetExt();
SourceTargetMapper.INSTANCE.sourceToTarget2( target, source );
assertResult( target );
}
@Test
@IssueKey("19")
public void existingMapping3() {
SourceExt source = createSource();
TargetExt target = new TargetExt();
TargetBase result = SourceTargetMapper.INSTANCE.sourceToTarget3( source, target );
assertThat( target ).isSameAs( result );
assertResult( target );
}
private void assertResult(TargetExt target) {
assertThat( target ).isNotNull();
assertThat( target.getFoo() ).isEqualTo( Long.valueOf( 42 ) );
assertThat( target.getBar() ).isEqualTo( 23 );
}
private SourceExt createSource() {
SourceExt source = new SourceExt();
source.setFoo( 42 );
source.setBar( 23L );
return source;
}
@Test
@IssueKey("17")
public void shouldReverseMapAttributeFromSuperType() {

View File

@ -20,6 +20,7 @@ package org.mapstruct.ap.test.inheritance;
import org.mapstruct.Mapper;
import org.mapstruct.Mappers;
import org.mapstruct.MappingTarget;
@Mapper
public interface SourceTargetMapper {
@ -28,5 +29,11 @@ public interface SourceTargetMapper {
TargetExt sourceToTarget(SourceExt source);
void sourceToTarget1(SourceExt source, TargetExt target);
void sourceToTarget2(@MappingTarget TargetExt target, SourceExt source);
TargetBase sourceToTarget3(SourceExt source, @MappingTarget TargetExt target);
SourceExt targetToSource(TargetExt target);
}