只能拿到 /** xxx */ 这样的注释,其他的先不琢磨了。
直接上代码吧
package comment;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskListener;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.parser.Tokens;
import com.sun.tools.javac.tree.DocCommentTable;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import javax.tools.SimpleJavaFileObject;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
public class CommentTest {
public static void main(String[] args) throws IOException {
// 1. 指定要提取注释的Java源文件路径
String filePath = "D:\\free-projects\\goodJob\\src\\test\\java\\comment\\User.java";
// 2. 读取源文件内容
String source = new String(Files.readAllBytes(new File(filePath).toPath()), StandardCharsets.UTF_8);
// 3. 创建Java编译器上下文
Context context = new Context();
// 4. 获取Java编译器实例
JavacTool javacTool = JavacTool.create();
// 5. 创建Java编译任务
JavacTask task = javacTool.getTask(null, null, null, null, null, List.of(new JavaSourceFromString(filePath, source)), context);
// 6. 注册任务监听器
task.addTaskListener(new TaskListener() {
@Override
public void started(TaskEvent taskEvent) {
}
@Override
public void finished(TaskEvent taskEvent) {
if (taskEvent.getKind() == TaskEvent.Kind.PARSE) {
CompilationUnitTree compilationUnit = taskEvent.getCompilationUnit();
if (compilationUnit == null) return;
// 7. 遍历AST树,提取注释
for (Tree tree : compilationUnit.getTypeDecls()) {
if (tree instanceof JCTree.JCClassDecl) {
JCTree.JCClassDecl classDecl = (JCTree.JCClassDecl) tree;
List<JCTree> members = classDecl.getMembers();
if (members != null && members.size() > 0){
for (JCTree member : members) {
if (!(member instanceof JCTree.JCVariableDecl)){
continue;
}
JCTree.JCVariableDecl variableDecl = (JCTree.JCVariableDecl) member;
DocCommentTable docComments = ((JCTree.JCCompilationUnit) compilationUnit).docComments;
Tokens.Comment comment = docComments.getComment(variableDecl);
System.out.print(variableDecl.getName().toString() + " " + variableDecl.getType().toString().toLowerCase() + (comment==null?"\n":comment.getText()));
}
}
}
}
}
}
});
// 8. 执行Java编译任务
task.call();
}
private static class JavaSourceFromString extends SimpleJavaFileObject {
private final String sourceCode;
public JavaSourceFromString(String name, String sourceCode) {
super(new File(name).toURI(), Kind.SOURCE);
this.sourceCode = sourceCode;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return sourceCode;
}
}
}
package comment;
import java.time.LocalDateTime;
public class User {
/**
* 用户id
*/
private Long userId;
/**
* 用户名
*/
private String userName;
/* 年龄 */
private int age;
// 创建时间
private LocalDateTime createTime;
}