Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Language IDEs » Java Development Tools (JDT) » Java : Import a class programmatically
Java : Import a class programmatically [message #1702517] Wed, 22 July 2015 19:48 Go to next message
Viktor Py is currently offline Viktor PyFriend
Messages: 1
Registered: July 2015
Junior Member
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 20:07]

Report message to a moderator

Re: Java : Import a class programmatically [message #1702525 is a reply to message #1702517] Wed, 22 July 2015 22:28 Go to previous message
Stephan Herrmann is currently offline Stephan HerrmannFriend
Messages: 1853
Registered: July 2009
Senior Member
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 Jun 18 02:30:00 GMT 2024

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

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

Back to the top