【问题标题】:Check class hierarchy at compile on an annotation processor在注释处理器上编译时检查类层次结构
【发布时间】:2015-04-30 15:42:41
【问题描述】:

我正在编写一个注解处理器来在编译时执行以下检查:

  • 有一个接口E
  • 有一个注解@Apply,用于注解方法。
  • @Apply注释的方法应该被称为apply并且只接受一个实现E的类的参数

到目前为止,我已经识别出所有名为apply 的带注释的方法,并提取了它们作为参数的类的名称。所以我只剩下:

 Element method  // this is the Element that represents the `apply` method
 TypeMirror mirror //method's TypeMirror
 String paramClass // the parameter's class Name.

问题是:如果有的话,我怎样才能摆脱这些参数的类层次结构表示,所以我可以检查它是否实现了E。 无法使用ClassLoader.loadClass,因为该类尚不存在,但我只需要类层次结构。

【问题讨论】:

    标签: java annotations jvm annotation-processing


    【解决方案1】:

    恰好有一个简单的方法使用javax.lang.model.util.Types.isSubtype() 方法:

     TypeMirror parameterTypes = mirror.getParameterTypes();
     TypeMirror typeOfE = processingEnv.getElementUtils().getTypeElement(E.class.getName()).asType();
     boolean isSubTypeOfE = processingEnv.getTypeUtils().isSubtype(parameterType, eventType)
    

    这样我可以检查mirror表示的方法的参数类是否是所需类型E的子类型

    【讨论】:

      猜你喜欢
      • 2015-06-06
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多