java中静态导入的正确使用
可能的重复:
静态导入的一个好的用例是什么方法?
我很少在java中看到这样的静态导入:
import static java.lang.Math.*;
然后你就可以访问PI
而无需调用Math.PI。
既然你不经常看到这种情况,这是否意味着这样做是一个糟糕的设计?
Possible Duplicate:
What is a good use case for static import of methods?
I rarely ever see a static import in java like this:
import static java.lang.Math.*;
Then you could access PI
without having to call Math.PI
.
Since you don't see this that often, does that mean it is a bad design to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不想使用它们,只是因为我想查看每个常量的定义位置。如果你的类和常量命名得当,那么它对可读性有很大帮助。
话又说回来,如果您使用同一类中的大量常量,并且它们的来源很明显,那么最好使用通配符导入。
I prefer not to use them, simply because I want to see where each constant is defined. If your classes and your constants are named appropriately, it helps readability a lot.
Then again, if you're using a lot of constants from the same class and it's obvious where they come from, you're better off with a wildcard import.
这不是一个糟糕的设计,但在我看来,
Math.PI
比PI
更易于维护。It is not bad design, but in my opinion
Math.PI
is clearer for maintaneinance than justPI
.有时是的。当您使用静态导入时,您静态导入的类中的字段和方法可能“看起来”来自您的类。
恕我直言,这确实会影响可理解性。
也就是说,我在 JUnit 测试中一直使用它!
Sometimes yes. When you use a static import, the fields and methods from the class you statically imported might "look like" they come from your class.
This does impact understandability, IMHO.
That said, I use it all the time in JUnit tests!
这还不错。只是通常没有必要。每当我的程序大量调用
java.lang.Math
时,我个人都会使用它。大多数人也不知道它,因为它很少被使用。同样的事情也适用于其他构造,例如静态构造函数。
It's not bad. It's just usually not necessary. I personally use it whenever my program uses a lot of calls to
java.lang.Math
.Most people also don't know about it since it's so infrequently used. Same thing goes to other constructs like static constructors.
数学在
import static
之前就已存在,这就是为什么大多数开发人员倾向于使用旧的形式。Math was around before
import static
which is why most developers would tend to use the older form.