是否可以通过参数访问字段注释,而无需将其名称用作字符串



是否可以从printTitle内部访问var@Anno实例?

class MyClass {
  @Anno(title="Title") Integer var;
  void someFunc() {
    printTitle(var);
  }
  public void printTitle(Integer param) {
    // How to get to the @Anno annotation?
    // Is it possible to get to the 'Field' where param is coming from?
    Anno anno = param. ... .getAnnotation(Anno.class);
    if(annotation != null) {
      ...
    }
  }
}

我不想将var的名称用作字符串"var"因为以后很难重构。

无法

String获取注解,需要一个表示String varField对象。

  void someFunc() {
    printTitle("var");
  }
  public void printTitle(String field) {
    Anno anno = getClass().getField(field).getAnnotation(Anno.class);
    if(annotation != null) {
      ...
    }
  }

最新更新