使用ASTParser(抽象语法树)获取类属性注释

   项目中有一个小任务,就是将项目中涵盖有哪些字段列举出来.思来想去,想到了AST可以读取到属性的注释,就免去了把字段获取后还需要填写中文名称的麻烦.

引入包

<!-- https://mvnrepository.com/artifact/de.defmacro/eclipse-astparser -->
        <dependency>
            <groupId>de.defmacro</groupId>
            <artifactId>eclipse-astparser</artifactId>
            <version>8.1</version>
        </dependency>

大体思路如下:

  1. ASTParser astParser = ASTParser.newParser(AST.JLS3);
  2. BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(文件路径));
  3. byte[] input = new byte[bufferedInputStream.available()];
  4. bufferedInputStream.read(input);
  5. bufferedInputStream.close();
  6. astParser.setKind(ASTParser.K_COMPILATION_UNIT);
  7. astParser.setSource(new String(input).toCharArray());
  8. CompilationUnit result = (CompilationUnit) (astParser.createAST(null));
  9. TypeDeclaration type = (TypeDeclaration) result.types().get(0);
  10. FieldDeclaration[] f = type.getFields();
  11. for (int j = 0; j < f.length; j++) {
  12. try {
  13. f[j].getJavadoc().toString()//获取每一个属性的注释
  14. f[j].fragments().get(0).toString()//获取属性字段
  15. //还需要获取属性字段名称.
  16. } catch (Exception e) {
  17. }
  18. }