Skip to content

Update AnnotationBuilder to not rely on toString() #2725

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.SimpleAnnotationValueVisitor8;

/**
* Generates an annotation implementation.
Expand Down Expand Up @@ -123,7 +125,21 @@ private static TypeSpec createBuilder(
FieldSpec.builder(field.type, field.name).addModifiers(Modifier.PRIVATE);
AnnotationValue value = annotationImpl.defaults.get(field);
if (value != null) {
fieldSpec.initializer("$L", value);
new SimpleAnnotationValueVisitor8<Void, Void>() {
@Override
public Void visitEnumConstant(VariableElement c, Void unused) {
// Using $L would print the simple name of the enum constant in JDK 17,
// see: https://github.com/square/javapoet/issues/845
fieldSpec.initializer("$T.$L", c.asType(), c.getSimpleName());
return null;
}

@Override
protected Void defaultAction(Object o, Void unused) {
fieldSpec.initializer("$L", value);
return null;
}
}.visit(value, null);
}
annotationBuilder.addMethod(
MethodSpec.methodBuilder(field.name)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public final class AtMyAnnotation {

private String strVal = "default";

private MyAnnotation.MyEnum enumVal = com.example.MyAnnotation.MyEnum.VALUE1;
private MyAnnotation.MyEnum enumVal = MyAnnotation.MyEnum.VALUE1;

public AtMyAnnotation intVal(int intVal) {
this.intVal = intVal;
Expand Down Expand Up @@ -224,4 +224,4 @@ public String toString() {
return sb.toString();
}
}
}
}