静态引入(Static Import)是Java引入的特性,它容许在类中定义public static
的成员(字段和方法),在使用时不用指定类名。此特性是在1.5版本中引入的。
该功能提供了一种类型安全的机制,能够没必要引用最初定义字段的类使用常量。它也有助于放弃建立常量接口:这是只定义了常量的接口,这种接口被认为是不合适的。
这种机制被用来引入类的单个成员:html
import static java.lang.Math.PI;
import static java.lang.Math.pow;
或者类的全部静态成员:java
import static java.lang.Math.*;
例如:安全
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("Considering a circle with a diameter of 5 cm, it has:");
System.out.println("A circumference of " + (Math.PI * 5) + " cm");
System.out.println("And an area of " + (Math.PI * Math.pow(2.5,2)) + " sq. cm");
}
}
上面的类能够改写成:markdown
import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
public static void main(String[] args) {
out.println("Hello World!");
out.println("Considering a circle with a diameter of 5 cm, it has:");
out.println("A circumference of " + (PI * 5) + " cm");
out.println("And an area of " + (PI * pow(2.5,2)) + " sq. cm");
}
}
歧义
若是多个类中名称相同的静态成员被引入,编译器会抛出错误,由于它不能断定使用哪一个类的成员。例如,下面代码会编译失败:oracle
import static java.lang.Integer.*;
import static java.lang.Long.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.println(MAX_VALUE);
}
}
MAX_VALUE
是有歧义的,由于MAX_VALUE
字段便是Integer的属性又是Long的属性。在字段前加上雷鸣能够消除歧义,但这样会形成静态引入冗余。ide
参考文章
http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
https://en.wikipedia.org/wiki/Static_import
http://viralpatel.net/blogs/static-import-java-example-tutorial/ui