java中静态导入的正确使用

发布于 2024-11-27 08:37:12 字数 362 浏览 4 评论 0原文

可能的重复:
静态导入的一个好的用例是什么方法?

我很少在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

握住你手 2024-12-04 08:37:12

我不想使用它们,只是因为我想查看每个常量的定义位置。如果你的类和常量命名得当,那么它对可读性有很大帮助。

话又说回来,如果您使用同一类中的大量常量,并且它们的来源很明显,那么最好使用通配符导入。

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.

故事和酒 2024-12-04 08:37:12

这不是一个糟糕的设计,但在我看来,Math.PIPI 更易于维护。

It is not bad design, but in my opinion Math.PI is clearer for maintaneinance than just PI.

走过海棠暮 2024-12-04 08:37:12

有时是的。当您使用静态导入时,您静态导入的类中的字段和方法可能“看起来”来自您的类。

恕我直言,这确实会影响可理解性。

也就是说,我在 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!

檐上三寸雪 2024-12-04 08:37:12

这还不错。只是通常没有必要。每当我的程序大量调用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.

痴骨ら 2024-12-04 08:37:12

数学在 import static 之前就已存在,这就是为什么大多数开发人员倾向于使用旧的形式。

Math was around before import static which is why most developers would tend to use the older form.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文