Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Java, can I import all packages at once?

Tags:

java

For example, the third party library uses very complex directory structure for the package. Can I import them at once. the star seems can only imports one directory level.

like image 275
user496949 Avatar asked Mar 15 '11 22:03

user496949


3 Answers

Assuming you're asking whether or not you can do something like:

import com.example.*;
// expecting packages like com.example.foo.* and com.example.bar.* to be imported

Then the answer is no. The widest import you can make is a single package with a star.

The JLS (section 7.5) defines the structure for import statements.

Additionally, it would be problematic for the compiler to import a bunch of packages at once. If two packages provide the same type, both are imported, and the type is used in the class, a compile-time error occurs. This is described in JLS 6.5.5.1:

Otherwise, if a type of that name is declared by more than one type-import-on-demand declaration of the compilation unit, then the name is ambiguous as a type name; a compile-time error occurs.

like image 139
Rob Hruska Avatar answered Oct 17 '22 05:10

Rob Hruska


As you pointed in java you can only use "one level" import used by "*"

The more effective way is to open Eclipse, open class where imports should be and press: CTRL + SHIFT + O:) - nowadays all IDE helps with organize imports

like image 4
lukastymo Avatar answered Oct 17 '22 04:10

lukastymo


I strongly suggest, as others have done, that you use the "organize imports" from your IDE (most major java IDE will do this).

Also, I advice against using "*" in your imports, and the reason for this is simple. At some time, you might want to upgrade one of the library that you import (or the jdk) and you might end up with name clashes due to some new classes in a package (this is especially true for the static imports). It might not be a big deal if that happens to a class inside your current project, but if you make that code into a library at some point, it might be more problematic as you will have to recompile that class after adjusting the conflicting imports.

(Yes, that happened to me not so long ago... It was a pain as I had to hunt down the library source code to rebuild.)

Save yourself some trouble down the road. :D

like image 3
Eric-Karl Avatar answered Oct 17 '22 04:10

Eric-Karl