-
Notifications
You must be signed in to change notification settings - Fork 30
Finding Annotations
Jon Schneider edited this page Nov 22, 2016
·
1 revision
Rewrite provides a shorthand for performing a search for annotations on classes, methods, and fields.
Let's start with an example annotation (the fact that this is a repeatable annotation is not a requirement in general):
package com.a;
import java.lang.annotation.Repeatable;
@Repeatable(Requests.class)
@interface Request {
String value();
String method() default "get";
}
Here is a class using the @Request
annotation:
import com.a.*;
@Request("/api") // 1
public class A {
@Request("/api") // 2
@Request(value = "/api") // 3
@Request(value = "/api", method = "get") // 4
public void apiEndpoint() {}
}
First, let's parse both classes and grab the Tr.CompilationUnit
of class A.
Tr.CompilationUnit cu = parser.parse(Arrays.asList(a, request)).get(0);
Tr.ClassDecl clazz = cu.getFirstClass();
We can retrieve a list of the Tr.Annotation
instances with (which matches all 4 annotations in our example, since it finds annotations both on class A
and those defined inside of it:
clazz.findAnnotations("@com.a.Request");
We can search more specifically on the method:
clazz.methods().stream()
.filter(m -> m.getSimpleName().equals("apiEndpoint"))
.findAny()
.map(m -> m.findAnnotations("@java.lang.Deprecated"))
.orElse(Collections.emptyList());
To match annotations only with the value parameter (matches 1 and 2):
clazz.findAnnotations("@com.a.Request(\"/api\")");
To match annotations with named parameters (matches 4):
// order does not matter
clazz.findAnnotations("@com.a.Request(default=\"/api\", method=\"get\")");
clazz.findAnnotations("@com.a.Request(method=\"get\", default=\"/api\")");