首页 > 解决方案 > 使用 Apache Bcel 获取注释名称

问题描述

我正在使用此代码来获取 Java 类注释:

JavaClass jclas = new ClassParser("src\\test\\org\\poc\\TestClass.class").parse();

ClassGen cg = new ClassGen(jclas);

AnnotationEntryGen[] attributes = cg.getAnnotationEntries();

for (AnnotationEntryGen attribute : attributes) {
    System.out.println("attribute: " + attribute);
    if(attribute.getTypeName().contains("Fix")) {
        // Do something
    }
}

但是当我打印时,attribute.getTypeName()我得到Lorg/annotations/Fix. 注释名称是@Fix(..) Do you know how I can get only the name?

标签: javaannotationsbcel

解决方案


像 `"Lorg/annotations/Fix" 这样的字符串是一个字段描述符。Java 有许多不同的类名格式

您可以使用反射实用程序包的Signatures在名称的不同格式之间进行转换。

注释名称是@Fix(..).

该术语不正确;您已经展示了完整的注解是如何用 Java 源代码编写的,但这不是它的名称。 getTypeName()确实返回了它的名称(以字段描述符格式)。

如果您想要注解的元素(当注解用 Java 源代码编写时出现在括号之间),请使用getValues(). 您可能还会发现toString()有用。


推荐阅读