Java 与导入相比,使用静态导入有什么优势吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18825640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are there any advantages of using static import over import?
提问by Ruchira Gayan Ranaweera
Consider the following class
考虑下面的类
public final class Constant {
public static final String USER_NAME="user1";
//more constant here
}
This class in the package B.
包 B 中的这个类。
Now I am going to use this in package A. Consider following two ways which can use.
现在我将在包 A 中使用它。考虑以下两种可以使用的方法。
Method 1- use import B.Constant
方法1-使用 import B.Constant
import B.Constant;
public class ValidateUser {
public static void main(String[] args) {
if(Constant.USER_NAME.equals("user1")){
}
}
}
Method 2- use import static B.Constant.USER_NAME;
方法2-使用 import static B.Constant.USER_NAME;
import static B.Constant.USER_NAME;
public class ValidateUser {
public static void main(String[] args) {
if(USER_NAME.equals("user1")){
}
}
}
My question is is there any difference or advantage normal import over static import in this case?
我的问题是在这种情况下,正常导入与静态导入有什么区别或优势吗?
采纳答案by Donal Fellows
The only difference between a normal import
and an import static
is that the latter is for moving static
members of some other class or interface — especiallyconstants — into scope. It's up to you whether you use it; I like it because it keeps the body of the class shorter, but YMMV.
normalimport
和 an之间的唯一区别import static
是后者用于将static
某些其他类或接口的成员(尤其是常量)移动到作用域中。是否使用由您决定;我喜欢它,因为它使类的主体更短,但是 YMMV。
There are no performance benefits or penalties to using them (except possibly when compiling, as if you care about that) as they compile into identical bytecode.
当它们编译成相同的字节码时,使用它们没有性能优势或损失(除非可能在编译时,就好像你关心它一样)。
回答by Sajan Chandran
The main difference is Readablity, Constant.USER_NAME
is less readable when compared to USER_NAME
.
主要的区别是可读性- ,Constant.USER_NAME
当相比是少可读USER_NAME
。
From Documentation:
从文档:
Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.
如果使用得当,静态导入可以通过删除类名重复的样板文件使您的程序更具可读性。
But in any case, try to avoid doing
但无论如何,尽量避免这样做
import static B.Constant.*;
import static B.Constant.*;
because it can pollute its namespace with all the static members you import.
因为它可以使用您导入的所有静态成员污染其命名空间。
回答by Husman
I use static imports very rarely and only where they actually make the code a little easier to follow.
我很少使用静态导入,并且只在它们实际上使代码更容易理解的地方使用。
According to oracle:
根据甲骨文:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html
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.
那么什么时候应该使用静态导入呢?非常节俭!仅当您试图声明常量的本地副本或滥用继承(常量接口反模式)时才使用它。换句话说,当您需要频繁访问一两个类的静态成员时使用它。如果您过度使用静态导入功能,它会使您的程序不可读和不可维护,您导入的所有静态成员都会污染其命名空间。你的代码的读者(包括你,在你编写它几个月后)不会知道静态成员来自哪个类。从类中导入所有静态成员对可读性特别有害;如果您只需要一两个成员,请单独导入它们。使用得当,静态导入可以让你的程序更具可读性,
The important points to note here:
这里需要注意的要点:
- Use it when you require frequent access to static members from one or two classes
- Used appropriately, static import can make your program more readable
- 当您需要频繁访问一两个类的静态成员时使用它
- 使用得当,静态导入可以让你的程序更具可读性
And commenter @Donal Fellows, says appropriately that using an IDE to manage static imports is less risky. I agree as modern IDE's have come a long way and will take out a lot of the pains of managing dependancies and tracing method calls back to a parent.
评论者@Donal Fellows 恰当地说,使用 IDE 管理静态导入的风险较小。我同意,因为现代 IDE 已经走了很长一段路,它将消除管理依赖项和跟踪方法调用回父级的许多痛苦。
回答by Maxim Shoustin
Static importslet you avoid qualifying static members with class names.
静态导入可让您避免使用类名限定静态成员。
Once the static member is imported then you can use it in your code without the class name prefix.
导入静态成员后,您就可以在代码中使用它而无需类名前缀。
Good example:
好的例子:
import static sample.SampleStaticValues.NUM_ZERO;
…
enum OddEven {odd,even}
//need not do SampleConstants.NUM_ZERO due to static import feature
if(num % 2 == NUM_ZERO){
System.out.println("The num " + num + " is: " + OddEven.even);
}
package sample;
public class SampleStaticValues {
public static int NUM_ZERO = 0;
public static int NUM_ONE = 0;
}
回答by Melih Alt?nta?
For example all methods in Math class are static an we call all of them as Math.mathod().But if we import math class like this : import static java.lang.Math.*;
We don't have to add Math before the method :
例如,Math 类中的所有方法都是静态的,我们称它们为 Math.mathod()。但是如果我们像这样导入 math 类:import static java.lang.Math.*;
我们不必在方法之前添加 Math:
import static java.lang.Math.*;
public class Program {
public static void main(String args[]) {
System.out.println(sqrt(25));
System.out.println(log(100));
System.out.println(PI);
}
}
回答by SpringLearner
In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say:
为了访问静态成员,必须使用它们来自的类来限定引用。例如,必须说:
double r = Math.cos(Math.PI * theta);
or
System.out.println("Blah blah blah");
You may want to avoid unnecessary use of static class members like Math. and System. For this use static import. For example above code when changed using static import is changed to:
您可能希望避免不必要地使用静态类成员,如 Math。和系统。为此,请使用静态导入。例如上面的代码在使用静态导入更改时更改为:
import static java.lang.System.out;
import static java.lang.Math.PI;
import static java.lang.Math.cos;
...
double r = cos(PI * theta);
out.println("Blah blah blah");
...
So whats the advantage of using above technique? Only advantage that I see is readability of the code. Instead of writing name of static class, one can directly write the method or member variable name. Also keep one thing in mind here. Ambiguous static import is not allowed. i.e. if you have imported java.lang.Math.PI and you want to import mypackage.Someclass.PI, the compiler will throw an error. Thus you can import only one member PI.
那么使用上述技术有什么好处呢?我看到的唯一优势是代码的可读性。可以直接写方法名或成员变量名,而不是写静态类的名字。还要记住一件事。不允许有歧义的静态导入。即如果你已经导入了 java.lang.Math.PI 并且你想要导入 mypackage.Someclass.PI,编译器会抛出一个错误。因此,您只能导入一个成员 PI。
回答by Rahul Agrawal
Static importsare used to save your time and typing. If you hate to type same thing again and again then you may find such imports interesting.
静态导入用于节省您的时间和输入。如果您讨厌一次又一次地输入相同的内容,那么您可能会发现此类导入很有趣。
The importallows the java programmer to access classes of a package without package qualification.
该进口允许Java程序员包的接入类,而包的资格。
The static importfeature allows to access the static members of a class without the class qualification.
在S tatic导入功能允许访问类的静态成员没有壹级资质。
Lets understand this with the help of below examples:
让我们借助以下示例来理解这一点:
Example 1: Without Static Imports
示例 1:没有静态导入
class Demo1{
public static void main(String args[])
{
double var1= Math.sqrt(5.0);
double var2= Math.tan(30);
System.out.println("Square of 5 is:"+ var1);
System.out.println("Tan of 30 is:"+ var2);
}
}
Output:
输出:
Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276
Example 2: Using Static Imports
示例 2:使用静态导入
import static java.lang.System.out;
import static java.lang.Math.*;
class Demo2{
public static void main(String args[])
{
//instead of Math.sqrt need to use only sqrt
double var1= sqrt(5.0);
//instead of Math.tan need to use only tan
double var2= tan(30);
//need not to use System in both the below statements
out.println("Square of 5 is:"+var1);
out.println("Tan of 30 is:"+var2);
}
}
Output:
输出:
Square of 5 is:2.23606797749979
Tan of 30 is:-6.405331196646276
回答by Hari Rao
Guys today we came across a big disadvantage of static imports. Just sharing it below.
伙计们,今天我们遇到了静态导入的一大缺点。下面简单分享一下。
- XXXConsts.java had EVENT_ID (EVENT_ID = "EVENT_ID") which was statically imported in a class XXXComceteImpl.java that extends from AbstractService.java
- XXXZeloImpl.java that extends from AbstractService.java wanted EVENT_ID = "eventId". So EVENT_ID = "eventId" was declared in AbstractService.java.
- Now #1 was broken as the EVENT_ID in XXXComceteImpl.java was referring to EVENT_ID in AbstractService.java
- May be the naming of EVENT_ID = "eventId" should have been different.
- Note:- Naming of the classed are redacted version so it looks unusual.
- XXXConsts.java 有 EVENT_ID (EVENT_ID = "EVENT_ID"),它静态导入到从 AbstractService.java 扩展的类 XXXComceteImpl.java 中
- 从 AbstractService.java 扩展的 XXXZeloImpl.java 想要 EVENT_ID = "eventId"。因此 EVENT_ID = "eventId" 在 AbstractService.java 中声明。
- 现在#1 被破坏了,因为 XXXComceteImpl.java 中的 EVENT_ID 指的是 AbstractService.java 中的 EVENT_ID
- 可能是 EVENT_ID = "eventId" 的命名应该不同。
- 注意:- 分类的命名是编辑版本,所以它看起来不寻常。