我怎么能打印一个注释的双引号字段的值,当它是一个字符串?例如:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation {
String myField();
}
@MyAnnotation(myField = "bla")
public class Test {
public static void main(String[] args) {
for (Annotation annotation : Test.class.getAnnotations()) {
System.out.println(annotation);
}
}
}
上面的代码产生:
@MyAnnotation(myField=bla)
如何将其更改为生成@MyAnnotation(myField="bla")
反射是唯一的方法:
for (Annotation annotation : Test.class.getAnnotations()) {
System.out.println(toString(annotation));
}
private String toString(Annotation annotation) throws InvocationTargetException, IllegalAccessException {
Map<String, Object> paramValues = getParamValues(annotation);
StringBuilder result = new StringBuilder("@")
.append(annotation.annotationType().getSimpleName())
.append("(");
for (Map.Entry<String, Object> param : paramValues.entrySet()) {
result.append(param.getKey()).append("="").append(param.getValue()).append("", ");
}
result.delete(result.length() - 2, result.length());
return result.append(")").toString();
}
private Map<String, Object> getParamValues(Annotation annotation) throws InvocationTargetException, IllegalAccessException {
Map<String, Object> params = new HashMap<>();
for (Method param : annotation.annotationType().getMethods()) {
if (param.getDeclaringClass() == annotation.annotationType()) { //this filters out built-in methods, like hashCode etc
params.put(param.getName(), param.invoke(annotation));
}
}
return params;
}
这将准确地打印你所要求的,对于任何类的任何注释(你只需要看看你想如何打印非字符串属性)。
但是…你为什么需要这个?
Annotation接口不提供对特定注释的任何见解。但是我认为你可以这样做:
public static void main(String[] args) {
for (Annotation annotation : Test.class.getAnnotations()) {
if (annotation instanceof MyAnnotation) {
... then you can cast to that specific type ...
... and then access/print
}
}
通常情况下,这种带有向下转换的instanceof检查应该避免,但是如果不这样做,我看不出有什么办法可以解决你的问题。