I am writing an Eclipse plug-in that should modify the source code in the Java editor. How can I figure the location of the source section like
- class declaration
- imports
- class fields
- methods
and so.
I am writing an Eclipse plug-in that should modify the source code in the Java editor. How can I figure the location of the source section like
and so.
You need to understand how the JDT works in Eclipse.
You could write something like this in a plugin:
IProject project = ResourcesPlugin.getWorkspace().getRoot()
.getProject(PROJECT_NAME);
IJavaProject javaProject = JavaCore.create(project);
IType type = project.findType(TYPE_NAME);
ICompilationUnit icu = type.getCompilationUnit();
Read Manipulating Java code to see what you can do with ICompilationUnit
.
If you want more options, you can generate an AST of your ICompilationUnit
, using for example:
CompilationUnit parse(ICompilationUnit unit)
{
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(unit);
parser.setResolveBindings(true);
return (CompilationUnit) parser.createAST(null);
}
Note that setting resolveBindings
to true
is expensive, so only do it when needed. CompilationUnit
is the root of your AST, which you can visit using an ASTVisitor. Agains see the previous document to see what you can do with ASTs.
Read the documentation online, check the API of the types involved, and try to find the source code of some example plugins.