很多人正在使用JavaParser实现最不同的目标。 其中之一是提取文档。 在这篇简短的文章中,我们将看到如何打印与类或接口关联的所有JavaDoc注释。
可以在GitHub上找到代码: https : //github.com/ftomassetti/javadoc-extractor
获取类的所有Javadoc注释
我们正在重用DirExplorer,在提出了支持类的介绍JavaParser类 。 此类允许递归处理目录,解析其中包含的所有Java文件。
我们可以从遍历所有类开始,然后找到相关的Javadoc注释。
/*** Iterate over the classes and print their Javadoc.*/
public class ClassesJavadocExtractor {public static void main(String[] args) {File projectDir = new File("source_to_parse/");new DirExplorer((level, path, file) -> path.endsWith(".java"), (level, path, file) -> {try {new VoidVisitorAdapter<Object>() {@Overridepublic void visit(ClassOrInterfaceDeclaration n, Object arg) {super.visit(n, arg);if (n.getComment() != null && n.getComment() instanceof JavadocComment) {String title = String.format("%s (%s)", n.getName(), path);System.out.println(title);System.out.println(Strings.repeat("=", title.length()));System.out.println(n.getComment());}}}.visit(JavaParser.parse(file), null);} catch (IOException e) {new RuntimeException(e);}}).explore(projectDir);}}
如您所见,获取JavaDoc注释非常容易。 它产生以下结果:
ASTParserConstants (/javaparser/javaparser-core/target/generated-sources/javacc/com/github/javaparser/ASTParserConstants.java)
==============================================================================================================================
/*** Token literal values and constants.* Generated by org.javacc.parser.OtherFilesGen#start()*/ParseException (/javaparser/javaparser-core/target/generated-sources/javacc/com/github/javaparser/ParseException.java)
======================================================================================================================
/*** This exception is thrown when parse errors are encountered.* You can explicitly create objects of this exception type by* calling the method generateParseException in the generated* parser.** You can modify this class to customize your error reporting* mechanisms so long as you retain the public fields.*/ASTParser (/javaparser/javaparser-core/target/generated-sources/javacc/com/github/javaparser/ASTParser.java)
============================================================================================================
/***
This class was generated automatically by javacc, do not edit.*/ ASTParserTokenManager (/javaparser/javaparser-core/target/generated-sources/javacc/com/github/javaparser/ASTParserTokenManager.java) ==================================================================================================================================== /** Token Manager. */
获取所有Javadoc注释并找到记录的元素
在其他情况下,我们可能要开始收集所有Javadoc注释,然后找到要注释的元素。 我们也可以使用Javaparser轻松做到这一点:
/*** Iterate over all the Javadoc comments and print them together with a description of the commented element.*/
public class AllJavadocExtractor {public static void main(String[] args) {File projectDir = new File("source_to_parse/");new DirExplorer((level, path, file) -> path.endsWith(".java"), (level, path, file) -> {try {new VoidVisitorAdapter<Object>() {@Overridepublic void visit(JavadocComment comment, Object arg) {super.visit(comment, arg);String title = null;if (comment.getCommentedNode().isPresent()) {title = String.format("%s (%s)", describe(comment.getCommentedNode().get()), path);} else {title = String.format("No element associated (%s)", path);}System.out.println(title);System.out.println(Strings.repeat("=", title.length()));System.out.println(comment);}}.visit(JavaParser.parse(file), null);} catch (IOException e) {new RuntimeException(e);}}).explore(projectDir);}private static String describe(Node node) {if (node instanceof MethodDeclaration) {MethodDeclaration methodDeclaration = (MethodDeclaration)node;return "Method " + methodDeclaration.getDeclarationAsString();}if (node instanceof ConstructorDeclaration) {ConstructorDeclaration constructorDeclaration = (ConstructorDeclaration)node;return "Constructor " + constructorDeclaration.getDeclarationAsString();}if (node instanceof ClassOrInterfaceDeclaration) {ClassOrInterfaceDeclaration classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration)node;if (classOrInterfaceDeclaration.isInterface()) {return "Interface " + classOrInterfaceDeclaration.getName();} else {return "Class " + classOrInterfaceDeclaration.getName();}}if (node instanceof EnumDeclaration) {EnumDeclaration enumDeclaration = (EnumDeclaration)node;return "Enum " + enumDeclaration.getName();}if (node instanceof FieldDeclaration) {FieldDeclaration fieldDeclaration = (FieldDeclaration)node;List<String> varNames = fieldDeclaration.getVariables().stream().map(v -> v.getName().getId()).collect(Collectors.toList());return "Field " + String.join(", ", varNames);}return node.toString();}}
在这里,大多数代码都是关于为注释节点提供描述的(方法describe )。
结论
操作AST并找到Javadoc注释非常容易。 但是,缺少的一项功能是可以以结构化形式提取Javadoc中包含的信息。 例如,您可能只想获取与某个参数或返回值关联的Javadoc部分。 Javaparser当前不具有此功能,但是我正在研究此功能,应该在接下来的1-2周内将其合并。 如果要关注开发,请查看问题433 。
感谢您的阅读和愉快的解析!
翻译自: https://www.javacodegeeks.com/2017/01/extracting-javadoc-documentation-source-files-using-javaparser.html