【问题标题】:Load the class dynamically and get the annotated classes动态加载类并获取注解的类
【发布时间】:2017-11-30 19:22:49
【问题描述】:
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

【问题讨论】:

  • 请提供更多关于“不起作用”的信息
  • 无法将工厂解析为类型。这是我看到的编译错误。它正在寻找 Factory.class 文件导入

标签: java class methods reflection


【解决方案1】:

你需要改变两件事:

  1. 工厂变量应该被转换为注解:

    Class&lt;Annotation&gt; Factorry = (Class&lt;Annotation&gt;)class.forName("com.this.class.Factory")

  2. 使用 Factory 变量而不是 Factory.class:

    roundEnv.getElementsAnnotatedWith(Factorry)

【讨论】:

  • 工厂工厂= method.getAnnotation(Factory);这会在相同的情况下工作吗?
  • 我无法回答,因为我不知道什么是工厂和方法?也许您应该发布另一个更详细的问题。
猜你喜欢
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多