How to redefine an import using Eclipse JDT Core

戏子无情 提交于 2020-02-06 19:33:47

问题


Does anyone have an example how to redefine an import in a java source file using the Eclipse JDT Core API?

I have the following (which does not work) and it's driving me mad.

try {
    for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
        if (root.getElementName().equals("src")) {
            for (ICompilationUnit unit : root.getPackageFragment("soap.service.implementation.strongProfile.delegate").getCompilationUnits()) {
                System.out.println(unit.getElementName());
                for (IImportDeclaration dec : unit.getImports()) {
                    dec.rename("soap.service.implementation.strongProfile.reader.HeadlineReader", true, null);
                }
            }
        }
    }
}catch(Exception e) {
    e.printStackTrace();
}

The exception I get is:

Java Model Exception: Java Model Status [Invalid name specified: soap.service.implementation.strongProfile.reader.HeadlineReader]

I take the import name and paste it in to my java source file and it's perfect, it doesn't give me any errors. Any help or guidance would be appreciated.


回答1:


Turns out this is a bug in Eclipse.




回答2:


I was stumbling over the same exception (even with Eclipse 3.7.2). This should be the bugreport: https://bugs.eclipse.org/bugs/show_bug.cgi?id=351940

Here is the solution that works(instead of the rename):

dec.delete(false, null);
unit.createImport(redefinedImport, null, dec.getFlags(), null);

Alternatively to get close to the original position

unit.createImport(redefinedImport, dec, dec.getFlags(), null);
dec.delete(false, null);

However this approach does not maintain the original positions of the import declarations. As my code contains comments and annotations the import declaration must be changed at the original position.

Directly manipulating the AST with ImportRewrite does also only allow a removeImport and addImport.

Is there any alternative solution to redefine/rename an import declaration programmatically?



来源:https://stackoverflow.com/questions/6671977/how-to-redefine-an-import-using-eclipse-jdt-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!