What does the “static” modifier after “import” mean?
当这样使用时:
1 2 3 | import static com.showboy.Myclass; public class Anotherclass{} |
参见文档
The static import declaration is
analogous to the normal import
declaration. Where the normal import
declaration imports classes from
packages, allowing them to be used
without package qualification, the
static import declaration imports
static members from classes, allowing
them to be used without class
qualification.So when should you use static import?
Very sparingly! Only use it when you'd
otherwise be tempted to declare local
copies of constants, or to abuse
inheritance (the Constant Interface
Antipattern). In other words, use it
when you require frequent access to
static members from one or two
classes. If you overuse the static
import feature, it can make your
program unreadable and unmaintainable,
polluting its namespace with all the
static members you import. Readers of
your code (including you, a few months
after you wrote it) will not know
which class a static member comes
from. Importing all of the static
members from a class can be
particularly harmful to readability;
if you need only one or two members,
import them individually. Used
appropriately, static import can make
your program more readable, by
removing the boilerplate of repetition
of class names.
你所说的这两种进口产品没有区别。但是,您可以使用静态导入来允许对其他类的静态成员进行不合格的访问。我以前必须这样做的地方:
1 2 3 4 5 6 7 8 | import org.apache.commons.lang.StringUtils; . . . if (StringUtils.isBlank(aString)) { . . . |
我能做到这一点:
1 2 3 4 5 6 7 8 | import static org.apache.commons.lang.StringUtils.isBlank; . . . if (isBlank(aString)) { . . . |
您可以在文档中看到更多信息。
静态导入用于导入类的静态字段/方法,而不是:
1 2 3 4 5 6 7 8 9 | package test; import org.example.Foo; class A { B b = Foo.B_INSTANCE; } |
你可以写:
1 2 3 4 5 6 7 8 9 | package test; import static org.example.Foo.B_INSTANCE; class A { B b = B_INSTANCE; } |
如果在代码中经常使用来自其他类的常量,并且静态导入不含糊,那么它很有用。
顺便说一句,在您的示例"import static org.example.myclass;"中不起作用:import用于类,import static用于类的静态成员。
静态导入的基本思想是,无论何时使用静态类、静态变量或枚举,都可以导入它们并保存自己以避免键入内容。
我将举例说明我的观点。
1 2 3 4 5 6 7 8 9 |
相同的代码,静态导入:
1 2 3 4 5 6 7 8 9 |
注意:静态导入可能会使您的代码难以阅读。
the difference between"import static com.showboy.Myclass" and"import com.showboy.Myclass"?
第一个应该生成一个编译器错误,因为静态导入只适用于导入字段或成员类型。(假设myClass不是内部类或Showboy的成员)
我想你是说
1 | import static com.showboy.MyClass.*; |
这使得MyClass中的所有静态字段和成员在实际编译单元中都可用,而不必限定它们…如上所述
EDCOX1〔8〕允许Java程序员访问包的类而无需封装验证。
例子:
随进口
1 2 3 4 5 6 7 8 9 |
带静态导入
1 2 3 4 5 6 7 8 9 |
参见:Java 5中的静态导入是什么?
假设在名为
注意:你需要做一个
在JavaJavaRebug中,EDCOX1 9是什么?这是一个非常好的资源,可以更好地了解EDCOX1和14。