Eclipse/Java - 导入 java.(namespace).* 有害吗?

2022-01-14 00:00:00 namespaces java eclipse

为什么 Eclipse 在导入类型时采用细粒度的方法?在 C# 中,我习惯于使用 System.Windows.Controls"并完成它,但 Eclipse 更喜欢单独导入我引用的每个小部件(使用 Ctrl+Shift+O 快捷方式).如果我知道我需要多个类型,那么导入整个命名空间有什么害处吗?

Why does Eclipse take a fine grained approach when importing types? In C# I'm used to things like "using System.Windows.Controls" and being done with it, but Eclipse prefers to import each widget I reference individually (using the Ctrl+Shift+O shortcut). Is there any harm to importing an entire namespace if I know I'll need multiple types in it?

推荐答案

通配符包导入可能造成的唯一危害是,如果多个包中存在多个同名类,则会增加命名空间冲突的机会.

The only harm that wildcard package imports can cause is an increased chance of namespace collisions if there are multiple classes of the same name in multiple packages.

例如,我想在 AWT 应用程序中使用 Java Collections Framework 的 ArrayList 类进行编程,该应用程序使用 List GUI 组件来显示信息.举个例子,假设我们有以下内容:

Say for example, I want to program to use the ArrayList class of the Java Collections Framework in an AWT application that uses a List GUI component to display information. For the sake of an example, let's suppose we have the following:

// 'ArrayList' from java.util
ArrayList<String> strings = new ArrayList<String>();

// ...

// 'List' from java.awt
List listComponent = new List()

现在,为了使用上述内容,必须至少导入这两个类:

Now, in order to use the above, there would have to be an import for those two classes, minimally:

import java.awt.List;
import java.util.ArrayList;

现在,如果我们在包 import 中使用通配符,我们会得到以下内容.

Now, if we were to use a wildcard in the package import, we'd have the following.

import java.awt.*;
import java.util.*;

但是,现在我们有一个问题!

However, now we will have a problem!

有一个 java.awt.List 类和一个 java.util.List,所以引用 List 类会很模糊.如果我们想消除歧义,就必须使用完全限定的类名来引用 List:

There is a java.awt.List class and a java.util.List, so referring to the List class would be ambiguous. One would have to refer to the List with a fully-qualified class name if we want to remove the ambiguity:

import java.awt.*;
import java.util.*;

ArrayList<String> strings = new ArrayList<String>();

// ...

// 'List' from java.awt -- need to use a fully-qualified class name.
java.awt.List listComponent = new java.awt.List()

因此,在某些情况下,使用通配符包 import 可能会导致问题.

Therefore, there are cases where using a wildcard package import can lead to problems.

相关文章