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.
Turns out this is a bug in Eclipse.
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):
Alternatively to get close to the original position
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?