我有一个程序可以更改Eclipse中加载的输入Java项目。更改后,我使用以下代码刷新项目并提取编译单元。

IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();

//projectName is the name of project loaded in eclipse
IProject project = root.getProject(projectName);

try {
    project.refreshLocal(IResource.DEPTH_INFINITE, null);
 } catch (CoreException e) {
        e.printStackTrace();
}

IJavaProject iJavaproject = JavaCore.create(project);

/** Extract ICompilationUnit. "classFullName" is the name of class contains new changes.*/
ICompilationUnit iCompilationUnit = getICompilationUnit(javaProject, classFullName);

/** Extract compilation unit.*/
CompilationUnit compilationUnit = getCompilationUnit(iCompilationUnit);


我有这两个函数来提取iCompilationUnit和CompilationUnit。

private ICompilationUnit getICompilationUnit(IJavaProject javaProject, String classFullName) {

    ICompilationUnit iUnit = null;
    try {
        IType iType = javaProject.findType(classFullName);
        iUnit = iType.getCompilationUnit();

        /** Create working copy. It is safer to work with a copy.*/
        WorkingCopyOwner owner = iUnit.getOwner();
        iUnit = (owner == null ? iUnit.getWorkingCopy(null) : iUnit.getWorkingCopy(owner, null));
    } catch (JavaModelException e) {
        e.printStackTrace();
    }

    return iUnit;
}

CompilationUnit getCompilationUnit(ICompilationUnit iCompilationUnit) {

    @SuppressWarnings("deprecation")
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(iCompilationUnit);

    /** we need bindings later on.*/
    parser.setResolveBindings(true);
    return (CompilationUnit) parser.createAST(null);
}


但是,我面临的问题是第一次调用此方法(第一次将任何更改应用于项目),以上代码无法检测到更改并返回原始版本。但是,此后,将正确刷新项目,并且最终的compilationUnit包含已应用的更改。

我不确定问题出在refreshLocal,还是其他两个函数:getCompilationUnit和getICompilationUnit。

如果有人有任何想法,请告诉我。

最佳答案

我认为JDT可能正在运行后台作业以重新编译和重建索引。因此,您需要等待这些工作完成。尝试

IJobManager jobManager = Job.getJobManager();

jobManager.join(ResourcesPlugin.FAMILY_MANUAL_BUILD, monitor);

jobManager.join(ResourcesPlugin.FAMILY_AUTO_BUILD, monitor);


refreshLocal之后但在执行其他操作之前执行此操作。

10-07 17:05