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

该项目旨在通过ASTParser来获取Java类的属性注释,以自动化列出所有字段及其对应的中文名称,避免手动填写。引入了de.defmacro/eclipse-astparser库,通过其提供的API解析抽象语法树,实现对类文件的深入分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   项目中有一个小任务,就是将项目中涵盖有哪些字段列举出来.思来想去,想到了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) {
            
    }
          
 }

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值