动态加载类并获取带注释的类

时间:2017-11-30 19:22:49

标签: java class methods reflection

import com.this.class.Factory;
      public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        // Itearate over all @Factory annotated elements
        for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {
            ...
        }
      }

当我在注释处理器中导入注释类时,这是有效的。但是当动态加载注释类时不起作用

Class<?> Factorry = class.forName("com.this.class.Factory")
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

        // Itearate over all @Factory annotated elements
        for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {
            ...
        }
      }

当使用class.forName()

加载类时,如何将带注释的Factory.class传递给getElementsAnnotatedWith

1 个答案:

答案 0 :(得分:1)

你需要改变两件事:

  1. 因子变量应该被转换为注释:

    Class<Annotation> Factorry = (Class<Annotation>)class.forName("com.this.class.Factory")

  2. 使用Factorry变量代替Factory.class:

    roundEnv.getElementsAnnotatedWith(Factorry)