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

//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
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
MethodDeclaration method = methods[i];
Javadoc doc = method.getJavadoc();
if(doc != null){
System.out.println(doc);
}
}



你可能感兴趣的:(JDT:获取Java类每个方法的注释)