Eclipse / Java - 是有害的导入java。(命名空间)。 [英] Eclipse/Java - is it harmful to import java.(namespace).*?

查看:119
本文介绍了Eclipse / Java - 是有害的导入java。(命名空间)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在导入类型时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.

例如,我想要编程使用使用 List GUI组件显示信息的AWT应用程序中的Java Collections Framework的 ArrayList 类。为了一个例子,让我们假设我们有以下内容:

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 ,所以参考列表类将是不明确的。如果我们想要消除歧义,则必须使用具有完全限定类名称的列表

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.

这篇关于Eclipse / Java - 是有害的导入java。(命名空间)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆