Copy over an annotation to generated code [message #734198] |
Thu, 06 October 2011 21:54  |
Eclipse User |
|
|
|
Hi,
I am writing an AnnotationProcessor, which has a requirement to copy over an annotation from source being processed to the generated code.
For instance, lets say I have the following input:
@Foo
public interface MyType {
@Bar(name="test")
void hello();
}
I can get the com.sun.mirror.declaration.AnnotationMirror object for "@Bar", but finding it hard to get valid Java from AST representation. Is there any utility or API which can give well-formed Java from AnnotationMirror object? I already tried toString but that does not give correct Java syntax.
Thanks.
|
|
|
Re: Copy over an annotation to generated code [message #734448 is a reply to message #734198] |
Fri, 07 October 2011 16:08  |
Eclipse User |
|
|
|
Here is what I ended up doing to implement this:
private void writeAnnotation(AnnotationMirror annotation) {
AnnotationTypeDeclaration annotationDeclaration = annotation.getAnnotationType().getDeclaration();
writer.print("@" + annotationDeclaration.getQualifiedName() + "(" );
Map<AnnotationTypeElementDeclaration, AnnotationValue> elementValues = annotation.getElementValues();
boolean isFirst = true;
for (Map.Entry<AnnotationTypeElementDeclaration, AnnotationValue> entry : elementValues.entrySet()) {
AnnotationTypeElementDeclaration elementKey = entry.getKey();
AnnotationValue elementValue = entry.getValue();
if (isFirst) {
isFirst = false;
} else {
writer.print(", ");
}
writer.print(elementKey.getSimpleName() + "=");
writeAnnotationValue(elementValue);
writer.println();
}
writer.println(")");
}
private void writeAnnotationValue(AnnotationValue annotationValue) {
Object value = annotationValue.getValue();
if (value instanceof String) {
String val = (String)value;
writer.print("\"");
writer.print(val);
writer.print("\"");
} else if (value instanceof AnnotationMirror) {
writeAnnotation((AnnotationMirror)value);
} else if (value instanceof TypeMirror) {
} else if (value instanceof EnumConstantDeclaration) {
EnumConstantDeclaration val = (EnumConstantDeclaration) value;
EnumDeclaration enumDecl = val.getDeclaringType();
String enumTypeName = enumDecl.getQualifiedName();
String simpleName = val.getSimpleName();
writer.print(enumTypeName + "." + simpleName);
} else if (value instanceof Collection) {
writer.print("{ ");
boolean isFirst = true;
for (AnnotationValue val: (Collection<AnnotationValue>)value) {
if (isFirst) {
isFirst = false;
} else {
writer.print(", ");
}
writeAnnotationValue(val);
}
writer.print(" }");
} else {
writer.print(value);
}
}
|
|
|
Powered by
FUDForum. Page generated in 0.05096 seconds