Reputation: 6912
Does Java support grouping the imports like following:
import package.{Class1,Class2}
I know that *
operator imports sub packages but I want to import specific ones.
In Rust
or some modern languages it is supported like following:
use package::{Class1, Class2};
Are there any alternative instead of writing each import line by line specifically like this?
import package.Class1;
import package.Class2;
Upvotes: 3
Views: 1078
Reputation: 159135
Java Language Specification, section 7.5. Import Declarations, shows:
An import declaration allows a named type or a
static
member to be referred to by a simple name (§6.2) that consists of a single identifier.[...]
A single-type-import declaration (§7.5.1) imports a single named type, by mentioning its canonical name (§6.7).
A type-import-on-demand declaration (§7.5.2) imports all the accessible types of a named type or named package as needed, by mentioning the canonical name of a type or package.
A single-static-import declaration (§7.5.3) imports all accessible
static
members with a given name from a type, by giving its canonical name.A static-import-on-demand declaration (§7.5.4) imports all accessible
static
members of a named type as needed, by mentioning the canonical name of a type.
As you can see, it's either a single named type, or all accessible types. No syntax for a list of types.
Side note: I almost never look at the import
statements of my code. I let Eclipse manage that for me (Source > Organize Imports... (Ctrl+Shift+O)), so I don't really care about having many single-type import statements. The section with the imports is collapsed anyway, so I don't even have to scroll past them. Oh the joy of using a good IDE.
Upvotes: 2
Reputation: 45329
No. Java doesn't have a construct to import a set of select classes using one statement. You either import all types from the package, or you import them one by one.
Using *
lets you import all classes from the same package (not to import sub-packages, as you mentioned):
import package.*; //Both Class1 and Class2 are imported
import static package.Class1.* //All static members of Class1 are imported
The first form import package.*
is usually discouraged because of the increased potential for name clashes (same class names from different packages). This is probably where import package.{Class1,Class2}
would have helped, but there's no such construct in Java.
Upvotes: 1
Reputation: 1129
In java, only supported ways to import multiple classes are as follows :
A - import individual classes
import package.Class1;
import package.Class2;
B - import all classes in a package or subpackage
import package.*;
import package.subpackage.*;
Refer Oracle doc for more information : https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Upvotes: 1