Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Language IDEs » Java Development Tools (JDT) » How to find import statements that are required for the block in AST Eclipse JDT?
How to find import statements that are required for the block in AST Eclipse JDT? [message #1785125] Mon, 09 April 2018 18:31 Go to next message
Fpt Telecom is currently offline Fpt TelecomFriend
Messages: 1
Registered: April 2018
Junior Member
This is my code snippet, here I try to create a new class from a extracted block from another class. Now I need to find what are all import statements required in the method that is extracted which has be added to the generated class.
private void generateClass() throws IOException {

    AST ast = AST.newAST(AST.JLS8);
    CompilationUnit unit = ast.newCompilationUnit();

    TypeDeclaration type = ast.newTypeDeclaration();
    type.setInterface(false);
    type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    type.setName(ast.newSimpleName("GeneratedClass"));

    MethodDeclaration methodDeclaration = identifyASTNode.getMethodDeclaration();
    methodDeclaration = (MethodDeclaration)ASTNode.copySubtree(ast, methodDeclaration);

    type.bodyDeclarations().add(methodDeclaration);

    unit.types().add(type);

    writeToFile(unit.toString());
}
Re: How to find import statements that are required for the block in AST Eclipse JDT? [message #1785354 is a reply to message #1785125] Thu, 12 April 2018 21:22 Go to previous message
Stephan Herrmann is currently offline Stephan HerrmannFriend
Messages: 1627
Registered: July 2009
Senior Member
Operations in JDT/UI (quick fix, refactoring ...) use org.eclipse.jdt.core.dom.rewrite.ImportRewrite for this purpose.

This works best in conjunction with an ASTRewrite performing all changes, rather than direct manipulation of the AST.
But applying text edits from ImportRewrite.rewriteImports() after creating that CU could still work, just never saw s.t. like that.
Perhaps the most tricky part is: you already need a CompilationUnit for ImportRewrite.create(..), but perhaps it's OK to pass an empty CU...

HTH,
Stephan
Previous Topic:Java9 mdoule - Problem between classpath / module-path
Next Topic:[V3.13.101] Type bindings for method invocations not resolved when enclosed in lambda expressions
Goto Forum:
  


Current Time: Thu Sep 20 09:05:48 GMT 2018

Powered by FUDForum. Page generated in 0.01396 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top