Skip to main content



      Home
Home » Language IDEs » Java Development Tools (JDT) » Java : Import a class programmatically
Java : Import a class programmatically [message #1702517] Wed, 22 July 2015 15:48 Go to next message
Eclipse UserFriend
I have a CompilationUnit that contains a class where a reference to another class is not imported. Eclipse resolves that kind of issue easily and proposes to import the missing class (which is located in the parent package).

How can I import a missing class programmatically without knowing its name or location ?

Reflection, injection, ClassLoader and other runtime mechanisms are not the right choice as I'm processing the classes statically through the Eclipse JDT API. Please, I'm just looking for a static oriented solution.
FYI : this how we list the imports from a CompilationUnit :
List<ImportDeclaration> existingImports = aCompilationUnit.imports();


The problem is that I don't know how to generate missing ImportDeclaration.

Thanks.

[Updated on: Wed, 22 July 2015 16:07] by Moderator

Re: Java : Import a class programmatically [message #1702525 is a reply to message #1702517] Wed, 22 July 2015 18:28 Go to previous message
Eclipse UserFriend
For manipulating the imports of a Java file please see class org.eclipse.jdt.core.dom.rewrite.ImportRewrite: the javadoc outlines its usage.
If all you have is an unresolvable simple name, utilities like ASTResolving.guessBindingForTypeReference(node) come in handy.
If that doesn't work for you, you may have to use the org.eclipse.jdt.core.search.SearchEngine and somehow cope with potentially many matches for a given simple name.

HTH,
Stephan
Previous Topic:Creating RPM from java code
Next Topic:Eclipse Mars: Forgets libraries, and can not add
Goto Forum:
  


Current Time: Tue Apr 22 16:43:09 EDT 2025

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

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

Back to the top