問題描述
為什么 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 應(yīng)用程序中使用 Java Collections Framework 的 ArrayList
類進行編程,該應(yīng)用程序使用 List
GUI 組件來顯示信息.舉個例子,假設(shè)我們有以下內(nèi)容:
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()
現(xiàn)在,為了使用上述內(nèi)容,必須至少導入這兩個類:
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;
現(xiàn)在,如果我們在包 import
中使用通配符,我們會得到以下內(nèi)容.
Now, if we were to use a wildcard in the package import
, we'd have the following.
import java.awt.*;
import java.util.*;
但是,現(xiàn)在我們有一個問題!
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.
這篇關(guān)于Eclipse/Java - 導入 java.(namespace).* 有害嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!