Suppose that I want to annotate a class with something like @RunWith(AndroidJUnit4.class)
. The general JavaPoet recipe would be:
private static ClassName RUN_WITH=ClassName.get("org.junit.runner", "RunWith");
private static ClassName ANDROID_JUNIT4=ClassName.get("android.support.test.runner", "AndroidJUnit4");
private TypeSpec buildTestClass() {
return TypeSpec.classBuilder("MainActivityTest")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(RUN_WITH)
.addMember(null, "$T.class", ANDROID_JUNIT4)
.build())
.build();
}
However, the two addMember()
methods on AnnotationSpec.Builder
each take a member name... and I do not want a name. I tried null
, as shown above, and that generates:
@RunWith(
null = AndroidJUnit4.class
)
So... how do we generate an "anonymous" (or whatever the proper term is for a single-unnamed-member) annotation?
The magic name to use is value
:
private static ClassName RUN_WITH=ClassName.get("org.junit.runner", "RunWith");
private static ClassName ANDROID_JUNIT4=ClassName.get("android.support.test.runner", "AndroidJUnit4");
private TypeSpec buildTestClass() {
return TypeSpec.classBuilder("MainActivityTest")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(AnnotationSpec.builder(RUN_WITH)
.addMember("value", "$T.class", ANDROID_JUNIT4)
.build())
.build();
}
This generates @RunWith(AndroidJUnit4.class)
as desired.