【问题标题】:Eclipse plug-in - Finding source parts locationEclipse 插件 - 查找源部件位置
【发布时间】:2009-11-02 12:38:54
【问题描述】:

我正在编写一个 Eclipse 插件,它应该在 Java 编辑器中修改源代码。 如何确定源部分的位置,如

  • 类声明
  • 进口
  • 类字段
  • 方法

等等。

【问题讨论】:

    标签: java eclipse eclipse-plugin


    【解决方案1】:

    您需要了解JDT 在 Eclipse 中的工作原理。

    你可以在插件中写这样的东西:

    IProject project = ResourcesPlugin.getWorkspace().getRoot()
        .getProject(PROJECT_NAME);
    IJavaProject javaProject = JavaCore.create(project);
    IType type = project.findType(TYPE_NAME);
    ICompilationUnit icu = type.getCompilationUnit();
    

    阅读Manipulating Java code,了解您可以使用ICompilationUnit 做什么。

    如果您需要更多选项,可以生成ICompilationUnit 的 AST,例如:

    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);
    }
    

    请注意,将resolveBindings 设置为true 的成本很高,因此请仅在需要时进行。 CompilationUnit 是您的 AST 的根,您可以使用 ASTVisitor 访问它。再次查看previous 文档,了解您可以使用 AST 做什么。

    在线阅读文档,查看所涉及类型的API,并尝试找到一些示例插件的源代码。

    【讨论】:

      【解决方案2】:

      您想修改Abstract Syntax Tree (AST)。

      【讨论】:

        猜你喜欢
        • 2021-01-10
        • 1970-01-01
        • 2014-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多