Reputation: 136
I have an annotation processor and I need to get the class associated with an element so I can retrieve its declared fields:
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
String className = null;
String packageName = null;
String fqClassName = null;
List<String> fields = new LinkedList<String>();
for (Element elem : roundEnv.getElementsAnnotatedWith(FieldConstant.class)) {
if (elem.getKind() == ElementKind.CLASS) {
// Encrypt encrypt = elem.getAnnotation(Encrypt.class);
// String message = "annotation found in " + elem.getSimpleName();
// processingEnv.getMessager().printMessage(Kind.NOTE, message);
TypeElement classElement = (TypeElement) elem;
PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();
className = classElement.getSimpleName().toString();
for(Field field : classElement.getClass().getDeclaredFields()){
do something...
}
.....
Obviously, className.getClass()
returns the TypeElement.class
but I want to retrieve the annotated class. How can I do that?
Upvotes: 3
Views: 1789
Reputation: 82461
You cannot use reflection on code being compiled normally, since the code may have been modified or generated in a previous pass (how would you add them to the classpath???).
However the good news is that you can use the packages in javax.lang.model
to get the properties of fields.
The following example prints all field definitions to System.out
(perhaps missing a few keywords such as transient
):
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (Element elem : roundEnv.getElementsAnnotatedWith(FieldConstant.class)) {
if (elem.getKind() == ElementKind.CLASS) {
// print fields
for (Element enclosedElement : elem.getEnclosedElements()) {
if (enclosedElement.getKind() == ElementKind.FIELD) {
Set<Modifier> modifiers = enclosedElement.getModifiers();
StringBuilder sb = new StringBuilder();
if (modifiers.contains(Modifier.PRIVATE)) {
sb.append("private ");
} else if (modifiers.contains(Modifier.PROTECTED)) {
sb.append("protected ");
} else if (modifiers.contains(Modifier.PUBLIC)) {
sb.append("public ");
}
if (modifiers.contains(Modifier.STATIC))
sb.append("static ");
if (modifiers.contains(Modifier.FINAL))
sb.append("final ");
sb.append(enclosedElement.asType()).append(" ").append(enclosedElement.getSimpleName());
System.out.println(sb);
}
}
}
}
...
Upvotes: 10