Skip to content

Commit 8dd8efc

Browse files
committed
Adapt ProtobbufAccessorNamingStrategy to work properly with builders
When the adder method is part of the protobuf builder then it's superclass it not the generated message Add list prefix to the element name when the enclosing element of the adder is assignable to protobuf MessageOrBuilder
1 parent 177e741 commit 8dd8efc

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

mapstruct-protobuf3/spi-impl/src/main/java/org/mapstruct/example/protobuf/ProtobufAccessorNamingStrategy.java

+19-10
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,41 @@
11
package org.mapstruct.example.protobuf;
22

3-
import org.mapstruct.ap.spi.DefaultAccessorNamingStrategy;
4-
53
import javax.lang.model.element.Element;
6-
import javax.lang.model.element.ElementKind;
74
import javax.lang.model.element.ExecutableElement;
85
import javax.lang.model.element.TypeElement;
96
import javax.lang.model.type.TypeMirror;
107

8+
import org.mapstruct.ap.spi.DefaultAccessorNamingStrategy;
9+
import org.mapstruct.ap.spi.MapStructProcessingEnvironment;
10+
1111
/**
1212
* @author Thomas Kratz
13+
* @author Filip Hrisafov
1314
*/
1415
public class ProtobufAccessorNamingStrategy extends DefaultAccessorNamingStrategy {
1516

16-
public static final String PROTOBUF_GENERATED_MESSAGE_V3 = "com.google.protobuf.GeneratedMessageV3";
17+
public static final String PROTOBUF_MESSAGE_OR_BUILDER = "com.google.protobuf.MessageOrBuilder";
1718
public static final String LIST_SUFFIX = "List";
1819

20+
protected TypeMirror protobufMesageOrBuilderType;
21+
22+
@Override
23+
public void init(MapStructProcessingEnvironment processingEnvironment) {
24+
super.init(processingEnvironment);
25+
26+
TypeElement typeElement = elementUtils.getTypeElement(PROTOBUF_MESSAGE_OR_BUILDER);
27+
if (typeElement != null) {
28+
protobufMesageOrBuilderType = typeElement.asType();
29+
}
30+
}
31+
1932
@Override
2033
public String getElementName(ExecutableElement adderMethod) {
2134

2235
String methodName = super.getElementName(adderMethod);
2336
Element receiver = adderMethod.getEnclosingElement();
24-
if (receiver != null && receiver.getKind() == ElementKind.CLASS) {
25-
TypeElement type = (TypeElement) receiver;
26-
TypeMirror superType = type.getSuperclass();
27-
if (superType != null && PROTOBUF_GENERATED_MESSAGE_V3.equals(superType.toString())) {
28-
methodName += LIST_SUFFIX;
29-
}
37+
if (receiver != null && protobufMesageOrBuilderType != null && typeUtils.isAssignable(receiver.asType(), protobufMesageOrBuilderType)) {
38+
methodName += LIST_SUFFIX;
3039
}
3140
return methodName;
3241
}

0 commit comments

Comments
 (0)