Annotation.toString()省略了String属性的双引号

时间:2016-11-01 19:23:29

标签: java reflection annotations

当它是字符串时,如何使用双引号打印注释字段的值? 例如:

@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")

2 个答案:

答案 0 :(得分:0)

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 
    }
}

通常情况下应该避免使用这种向下检查的实例,但我没有找到解决问题的方法而不这样做。

答案 1 :(得分:0)

反思是唯一的方法:

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;
}

这将完全打印您要求的内容,以及任何类的任何注释(您只需要看看如何打印非字符串属性)。

但是......你为什么要这个?

相关问题