项目中有一个小任务,就是将项目中涵盖有哪些字段列举出来.思来想去,想到了AST可以读取到属性的注释,就免去了把字段获取后还需要填写中文名称的麻烦.
引入包
<!-- https://mvnrepository.com/artifact/de.defmacro/eclipse-astparser -->
<dependency>
<groupId>de.defmacro</groupId>
<artifactId>eclipse-astparser</artifactId>
<version>8.1</version>
</dependency>
大体思路如下:
- ASTParser astParser = ASTParser.newParser(AST.JLS3);
- BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(文件路径));
- byte[] input = new byte[bufferedInputStream.available()];
- bufferedInputStream.read(input);
- bufferedInputStream.close();
- astParser.setKind(ASTParser.K_COMPILATION_UNIT);
- astParser.setSource(new String(input).toCharArray());
- CompilationUnit result = (CompilationUnit) (astParser.createAST(null));
- TypeDeclaration type = (TypeDeclaration) result.types().get(0);
- FieldDeclaration[] f = type.getFields();
- for (int j = 0; j < f.length; j++) {
- try {
- f[j].getJavadoc().toString()//获取每一个属性的注释
- f[j].fragments().get(0).toString()//获取属性字段
- //还需要获取属性字段名称.
-
- } catch (Exception e) {
-
- }
-
- }