#853 Enable support for Iterable / Map classes which are not generic, like they are generated by JAXB (e.g. public class StringList extends List<String>)

This commit is contained in:
stefan.may 2016-08-02 09:25:45 +02:00 committed by Andreas Gudian
parent 9753fdc17a
commit 1be3c4dbaa
11 changed files with 209 additions and 17 deletions

View File

@ -92,10 +92,12 @@ public class IterableMappingMethod extends MappingMethod {
Type sourceParameterType = first( method.getSourceParameters() ).getType(); Type sourceParameterType = first( method.getSourceParameters() ).getType();
Type resultType = method.getResultType(); Type resultType = method.getResultType();
Type sourceElementType = sourceParameterType.isArrayType() ? sourceParameterType.getComponentType() Type sourceElementType =
: first( sourceParameterType.getTypeParameters() ).getTypeBound(); sourceParameterType.isArrayType() ? sourceParameterType.getComponentType() : first(
Type targetElementType = resultType.isArrayType() ? resultType.getComponentType() sourceParameterType.determineTypeArguments( Iterable.class ) ).getTypeBound();
: first( resultType.getTypeParameters() ).getTypeBound(); Type targetElementType =
resultType.isArrayType() ? resultType.getComponentType() : first(
resultType.determineTypeArguments( Iterable.class ) ).getTypeBound();
String loopVariableName = String loopVariableName =
Strings.getSaveVariableName( sourceElementType.getName(), method.getParameterNames() ); Strings.getSaveVariableName( sourceElementType.getName(), method.getParameterNames() );
@ -251,7 +253,7 @@ public class IterableMappingMethod extends MappingMethod {
return sourceParameterType.getComponentType(); return sourceParameterType.getComponentType();
} }
else { else {
return sourceParameterType.getTypeParameters().get( 0 ).getTypeBound(); return sourceParameterType.determineTypeArguments( Iterable.class ).get( 0 ).getTypeBound();
} }
} }
@ -260,7 +262,7 @@ public class IterableMappingMethod extends MappingMethod {
return getResultType().getComponentType(); return getResultType().getComponentType();
} }
else { else {
return getResultType().getTypeParameters().get( 0 ); return getResultType().determineTypeArguments( Iterable.class ).get( 0 );
} }
} }

View File

@ -21,6 +21,7 @@ package org.mapstruct.ap.internal.model;
import static org.mapstruct.ap.internal.util.Collections.first; import static org.mapstruct.ap.internal.util.Collections.first;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import org.mapstruct.ap.internal.model.assignment.Assignment; import org.mapstruct.ap.internal.model.assignment.Assignment;
@ -96,8 +97,9 @@ public class MapMappingMethod extends MappingMethod {
public MapMappingMethod build() { public MapMappingMethod build() {
List<Type> sourceTypeParams = first( method.getSourceParameters() ).getType().getTypeParameters(); List<Type> sourceTypeParams =
List<Type> resultTypeParams = method.getResultType().getTypeParameters(); first( method.getSourceParameters() ).getType().determineTypeArguments( Map.class );
List<Type> resultTypeParams = method.getResultType().determineTypeArguments( Map.class );
// find mapping method or conversion for key // find mapping method or conversion for key
Type keySourceType = sourceTypeParams.get( 0 ).getTypeBound(); Type keySourceType = sourceTypeParams.get( 0 ).getTypeBound();
@ -217,6 +219,15 @@ public class MapMappingMethod extends MappingMethod {
throw new IllegalStateException( "Method " + this + " has no source parameter." ); throw new IllegalStateException( "Method " + this + " has no source parameter." );
} }
public List<Type> getSourceElementTypes() {
Type sourceParameterType = getSourceParameter().getType();
return sourceParameterType.determineTypeArguments( Map.class );
}
public List<Type> getResultElementTypes() {
return getResultType().determineTypeArguments( Map.class );
}
public Assignment getKeyAssignment() { public Assignment getKeyAssignment() {
return keyAssignment; return keyAssignment;
} }

View File

@ -790,4 +790,30 @@ public class Type extends ModelElement implements Comparable<Type> {
} }
return hasEmptyAccessibleContructor; return hasEmptyAccessibleContructor;
} }
/**
* Searches for the given superclass and collects all type arguments for the given class
*
* @param superclass the superclass or interface the generic type arguments are searched for
* @return a list of type arguments or null, if superclass was not found
*/
public List<Type> determineTypeArguments(Class<?> superclass) {
TypeMirror superclassMirror =
typeUtils.erasure( elementUtils.getTypeElement( superclass.getCanonicalName() ).asType() );
if ( typeUtils.isAssignable( superclassMirror, typeMirror )
&& typeUtils.isAssignable( typeMirror, superclassMirror ) ) {
return getTypeParameters();
}
List<? extends TypeMirror> directSupertypes = typeUtils.directSupertypes( typeMirror );
for ( TypeMirror supertypemirror : directSupertypes ) {
Type supertype = typeFactory.getType( supertypemirror );
List<Type> supertypeTypeArguments = supertype.determineTypeArguments( superclass );
if ( supertypeTypeArguments != null ) {
return supertypeTypeArguments;
}
}
return null;
}
} }

View File

@ -133,8 +133,7 @@
<#if resultType.implementationType??> <#if resultType.implementationType??>
<@includeModel object=resultType.implementationType/> <@includeModel object=resultType.implementationType/>
<#else> <#else>
<@includeModel object=resultType/> <@includeModel object=resultType/></#if>()
</#if>()
</#if> </#if>
</@compress> </@compress>
</#macro> </#macro>

View File

@ -56,11 +56,11 @@
<#-- key --> <#-- key -->
<@includeModel object=keyAssignment <@includeModel object=keyAssignment
targetWriteAccessorName=keyVariableName targetWriteAccessorName=keyVariableName
targetType=resultType.typeParameters[0].typeBound/> targetType=resultElementTypes[0].typeBound/>
<#-- value --> <#-- value -->
<@includeModel object=valueAssignment <@includeModel object=valueAssignment
targetWriteAccessorName=valueVariableName targetWriteAccessorName=valueVariableName
targetType=resultType.typeParameters[1].typeBound/> targetType=resultElementTypes[1].typeBound/>
${resultName}.put( ${keyVariableName}, ${valueVariableName} ); ${resultName}.put( ${keyVariableName}, ${valueVariableName} );
} }
<#list afterMappingReferences as callback> <#list afterMappingReferences as callback>
@ -91,8 +91,7 @@
<#if resultType.implementationType??> <#if resultType.implementationType??>
<@includeModel object=resultType.implementationType /> <@includeModel object=resultType.implementationType />
<#else> <#else>
<@includeModel object=resultType /> <@includeModel object=resultType /></#if>()
</#if>()
</#if> </#if>
</@compress> </@compress>
</#macro> </#macro>

View File

@ -29,13 +29,15 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.fest.assertions.MapAssert;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mapstruct.ap.testutil.IssueKey; import org.mapstruct.ap.testutil.IssueKey;
import org.mapstruct.ap.testutil.WithClasses; import org.mapstruct.ap.testutil.WithClasses;
import org.mapstruct.ap.testutil.runner.AnnotationProcessorTestRunner; import org.mapstruct.ap.testutil.runner.AnnotationProcessorTestRunner;
@WithClasses({ Source.class, Target.class, Colour.class, SourceTargetMapper.class, TestList.class, TestMap.class }) @WithClasses({ Source.class, Target.class, Colour.class, SourceTargetMapper.class, TestList.class, TestMap.class,
TestNonGenericList.class, StringToLongMap.class })
@RunWith(AnnotationProcessorTestRunner.class) @RunWith(AnnotationProcessorTestRunner.class)
public class CollectionMappingTest { public class CollectionMappingTest {
@ -389,4 +391,56 @@ public class CollectionMappingTest {
assertThat( source.getEnumSet() ).containsOnly( Colour.BLUE, Colour.GREEN, Colour.RED ); assertThat( source.getEnumSet() ).containsOnly( Colour.BLUE, Colour.GREEN, Colour.RED );
assertThat( target.getEnumSet() ).containsOnly( Colour.BLUE, Colour.GREEN ); assertThat( target.getEnumSet() ).containsOnly( Colour.BLUE, Colour.GREEN );
} }
@Test
@IssueKey("TODO")
public void shouldMapNonGenericList() {
Source source = new Source();
source.setStringList3( new ArrayList<String>( Arrays.asList( "Bob", "Alice" ) ) );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getNonGenericStringList() ).containsExactly( "Bob", "Alice" );
// Inverse direction
Target newTarget = new Target();
TestNonGenericList nonGenericStringList = new TestNonGenericList();
nonGenericStringList.addAll( Arrays.asList( "Bill", "Bob" ) );
newTarget.setNonGenericStringList( nonGenericStringList );
Source mappedSource = SourceTargetMapper.INSTANCE.targetToSource( newTarget );
assertThat( mappedSource ).isNotNull();
assertThat( mappedSource.getStringList3() ).containsExactly( "Bill", "Bob" );
}
@Test
@IssueKey("TODO")
public void shouldMapNonGenericMap() {
Source source = new Source();
Map<String, Long> map = new HashMap<String, Long>();
map.put( "Bob", 123L );
map.put( "Alice", 456L );
source.setStringLongMapForNonGeneric( map );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getNonGenericMapStringtoLong() ).includes( MapAssert.entry( "Bob", 123L ),
MapAssert.entry( "Alice", 456L ) );
// Inverse direction
Target newTarget = new Target();
StringToLongMap stringToLongMap = new StringToLongMap();
stringToLongMap.put( "Blue", 321L );
stringToLongMap.put( "Green", 654L );
newTarget.setNonGenericMapStringtoLong( stringToLongMap );
Source mappedSource = SourceTargetMapper.INSTANCE.targetToSource( newTarget );
assertThat( mappedSource ).isNotNull();
assertThat( mappedSource.getStringLongMapForNonGeneric() ).includes( MapAssert.entry( "Blue", 321L ),
MapAssert.entry( "Green", 654L ) );
}
} }

View File

@ -49,12 +49,16 @@ public class Source {
private Map<String, Long> otherStringLongMap; private Map<String, Long> otherStringLongMap;
private Map<String, Long> stringLongMapForNonGeneric;
private List<String> stringList2; private List<String> stringList2;
private Set<String> stringSet2; private Set<String> stringSet2;
private EnumSet<Colour> enumSet; private EnumSet<Colour> enumSet;
private List<String> stringList3;
public List<String> getStringList() { public List<String> getStringList() {
return stringList; return stringList;
} }
@ -174,4 +178,20 @@ public class Source {
public void setEnumSet(EnumSet<Colour> enumSet) { public void setEnumSet(EnumSet<Colour> enumSet) {
this.enumSet = enumSet; this.enumSet = enumSet;
} }
public List<String> getStringList3() {
return stringList3;
}
public void setStringList3(List<String> stringList3) {
this.stringList3 = stringList3;
}
public Map<String, Long> getStringLongMapForNonGeneric() {
return stringLongMapForNonGeneric;
}
public void setStringLongMapForNonGeneric(Map<String, Long> stringLongMapForNonGeneric) {
this.stringLongMapForNonGeneric = stringLongMapForNonGeneric;
}
} }

View File

@ -38,7 +38,9 @@ public interface SourceTargetMapper {
@Mapping(source = "integerSet", target = "set"), @Mapping(source = "integerSet", target = "set"),
@Mapping(source = "anotherIntegerSet", target = "anotherStringSet"), @Mapping(source = "anotherIntegerSet", target = "anotherStringSet"),
@Mapping(source = "stringList2", target = "stringListNoSetter"), @Mapping(source = "stringList2", target = "stringListNoSetter"),
@Mapping(source = "stringSet2", target = "stringListNoSetter2") @Mapping(source = "stringSet2", target = "stringListNoSetter2"),
@Mapping(source = "stringList3", target = "nonGenericStringList"),
@Mapping(source = "stringLongMapForNonGeneric", target = "nonGenericMapStringtoLong")
}) })
Target sourceToTarget(Source source); Target sourceToTarget(Source source);

View File

@ -0,0 +1,30 @@
/**
* Copyright 2012-2016 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.ap.test.collection;
import java.util.HashMap;
/**
* @author Stefan May
*/
public class StringToLongMap extends HashMap<String, Long> {
private static final long serialVersionUID = 1L;
}

View File

@ -58,6 +58,10 @@ public class Target {
private EnumSet<Colour> enumSet; private EnumSet<Colour> enumSet;
private TestNonGenericList nonGenericStringList;
private StringToLongMap nonGenericMapStringtoLong;
public Target() { public Target() {
otherStringLongMap = Maps.newHashMap(); otherStringLongMap = Maps.newHashMap();
otherStringLongMap.put( "not-present-after-mapping", 42L ); otherStringLongMap.put( "not-present-after-mapping", 42L );
@ -184,4 +188,20 @@ public class Target {
public void setEnumSet(EnumSet<Colour> enumSet) { public void setEnumSet(EnumSet<Colour> enumSet) {
this.enumSet = enumSet; this.enumSet = enumSet;
} }
public TestNonGenericList getNonGenericStringList() {
return nonGenericStringList;
}
public void setNonGenericStringList(TestNonGenericList nonGenericStringList) {
this.nonGenericStringList = nonGenericStringList;
}
public StringToLongMap getNonGenericMapStringtoLong() {
return nonGenericMapStringtoLong;
}
public void setNonGenericMapStringtoLong(StringToLongMap nonGenericMapStringtoLong) {
this.nonGenericMapStringtoLong = nonGenericMapStringtoLong;
}
} }

View File

@ -0,0 +1,29 @@
/**
* Copyright 2012-2016 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.ap.test.collection;
import java.util.ArrayList;
/**
* @author Stefan May
*/
public class TestNonGenericList extends ArrayList<String> {
private static final long serialVersionUID = 1L;
}