JDT:获取Java类每个方法的注释

来源:互联网 发布:java 项目经验编写 编辑:程序博客网 时间:2024/05/18 20:07
//step1:获取ICompilationUnit 
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("test");
try {
project.open(null /* IProgressMonitor */);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
IJavaProject javaProject = JavaCore.create(project);
IType lwType = null;
try {
lwType = javaProject.findType("net.chenxs.Test");
} catch (JavaModelException e) {
e.printStackTrace();
}

//step2:提取JavaDoc
ICompilationUnit lwCompilationUnit = lwType.getCompilationUnit();
 try {
SourceType type = (SourceType) lwCompilationUnit.getAllTypes()[0];
IBuffer buffer = lwCompilationUnit.getBuffer();
IMethod[] methods = type.getMethods();
IBuffer buffer1 = lwCompilationUnit.getBuffer();
for(int i=0; i<methods.length;i++){
IMethod method =methods[i];
ISourceRange range = method.getJavadocRange();//获取JavaDoc的范围区间
if(range != null){
System.out.println(range.getOffset() + "  " + range.getLength());
System.out.println(buffer1.getText(range.getOffset(),range.getLength()));;
}
}
} catch (JavaModelException e) {
e.printStackTrace();
}

注:通过ast也是可以的;
ASTParser  astParser = ASTParser.newParser(AST.JLS3);
astParser.setKind(ASTParser.K_COMPILATION_UNIT);
astParser.setSource(lwCompilationUnit);
CompilationUnit unit = (CompilationUnit) astParser.createAST(null);
TypeDeclaration type =  (TypeDeclaration) unit.types().get(0);
MethodDeclaration[] methods = type.getMethods();
for(int i=0; i<methods.length;i++){
    MethodDeclaration method = methods[i];
   Javadoc doc = method.getJavadoc();
 if(doc != null){
System.out.println(doc);
      }
}



原创粉丝点击