【问题标题】:Instantiate a Class annotated with some annotation实例化一个带有一些注解的类
【发布时间】:2017-06-16 14:59:54
【问题描述】:

我想通过在注解处理器中获取注解,从存在特定注解的类中获取有关字段的信息。

我可以从注释中检索完全限定的类名,但不能实例化它,ClassNotFoundException 被抛出,尽管类在那里。

如何检查类是否不在类路径中或注释处理器包含哪个类路径?

try {
                Class<?> clazz = Class.forName(((TypeElement) e).getQualifiedName().toString());
            } catch (ClassNotFoundException cnfe) {
                cnfe.printStackTrace();
            }

【问题讨论】:

  • toString() 返回什么路径?
  • 它返回我的 Android 应用程序中一个类的类路径。

标签: java annotations annotation-processing annotation-processor


【解决方案1】:

您在问题代码中尝试执行的操作是不可能的,因为注释处理发生在程序完全编译之前。这就是为什么你使用例如TypeElement 对象而不是 Class,因为该类尚未编译。

另一方面,如果您只想检查存在哪些类型的字段,you can use the Element API for that,例如:

for (Element e : typeElement.getEnclosedElements()) {
    if (e.getKind() == ElementKind.FIELD) {
        VariableElement field = (VariableElement) e;
        //
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2021-10-13
    相关资源
    最近更新 更多