导入语句中使用通配符不好

导入语句中使用通配符不好

本文介绍了为什么在 Java 导入语句中使用通配符不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用像这样的单个语句更方便、更简洁

It is much more convenient and cleaner to use a single statement like

import java.awt.*;

而不是导入一堆单独的类

than to import a bunch of individual classes

import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...

import 语句中使用通配符有什么问题?

What is wrong with using a wildcard in the import statement?

推荐答案

它唯一的问题是它使您的本地命名空间变得混乱.例如,假设您正在编写一个 Swing 应用程序,因此需要 java.awt.Event,并且还与公司的日历系统交互,该系统具有 com.mycompany.calendar.事件.如果您使用通配符方法导入两者,则会发生以下三种情况之一:

The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:

  1. 您在 java.awt.Eventcom.mycompany.calendar.Event 之间存在明显的命名冲突,因此您甚至无法编译.
  2. 你实际上只导入了一个(你的两个导入中只有一个是 .*),但它是错误的,你很难弄清楚为什么你的代码声称类型是错误的.
  3. 当您编译代码时,没有 com.mycompany.calendar.Event,但是当他们稍后添加一个时,您以前有效的代码突然停止编译.
  1. You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
  2. You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
  3. When you compile your code there is no com.mycompany.calendar.Event, but when they later add one your previously valid code suddenly stops compiling.

显式列出所有导入的优点是我一眼就能看出您打算使用哪个类,这使得阅读代码变得更加容易.如果你只是做一件一次性的快速事情,没有什么明显的错误,但未来的维护者会感谢你的清晰.

The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.

这篇关于为什么在 Java 导入语句中使用通配符不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:30