简体   繁体   中英

Eclipse plug-in - Finding source parts location

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.

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.

您要修改抽象语法树 (AST)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM