当简单名称和完全限定名称发生冲突时如何引用类 [英] How to refer to a class when both simple and fully-qualified names clash
问题描述
请考虑以下病理示例:
class Ideone {
static class ArrayList<T> {
ArrayList() {
System.out.println("!!");
}
}
static class java {
static class util {
static class ArrayList<T> {
ArrayList() {
System.out.println("Here");
}
}
}
}
public static void main(String[] args) {
new ArrayList<>();
new java.util.ArrayList<>();
// Can I refer to the "usual" java.util.ArrayList?
}
}
在构造函数中创建的两个实例属于嵌套类.
The two instances created in the constructor are of the nested classes.
但是我怎么可能引用 我们都在同一个类中认识并喜欢的java.util.ArrayList
?我们不能导入它,也不能使用完全限定的名称,因为将使用嵌套的类符号.
But how might I refer to the java.util.ArrayList
that we all know and love in the same class? We can't import it, and we can't use the fully-qualified name, as the nested class symbols would be used instead.
在这种情况下我们该怎么办?(除了显而易见的以外-停止对嵌套类使用这样的肆意邪恶名称).
What can we do in this case? (Other than the obvious - stop using such wantonly evil names for the nested classes).
推荐答案
如果您已完成以下两项操作,则不能再直接引用 java.util.ArrayList
:>
You can no longer directly reference java.util.ArrayList
if you've done the 2 things you've done:
- 在作用域中使用静态嵌套类隐藏简单名称
ArrayList
. - 使用嵌套在类
util
中,嵌套在嵌套类中的类
.ArrayList
隐藏全限定名java.util.ArrayList
java
- Hide the simple name
ArrayList
with a static nested class in scope. - Hide the fully qualified name
java.util.ArrayList
with a classArrayList
nested within classutil
, nested within nested classjava
.
您甚至无法拆分"导入,以尝试使用部分合格"的导入.
You can't even "split" the import in an attempt to use a "partially qualified" import.
import java.*;
...
// This doesn't work!
new util.ArrayList<>();
您可以 import java.*;
,但这毫无价值;没有直接在 java
包中定义任何类.
You can import java.*;
, but that is worthless; no classes are defined in the java
package directly.
但是,您可以间接引用类 java.util.ArrayList
,因为它不是 final
.在类 Ideone
的范围之外,声明一个具有不同名称的子类.
However, you can reference the class java.util.ArrayList
indirectly because it's not final
. Outside the scope of the class Ideone
, declare a subclass with a different name.
class AnArrayList<T> extends java.util.ArrayList<T> {}
然后您可以在接口中引用该类和程序:
Then you can refer to that class and program to the interface:
List<Integer> al = new AnArrayList<>(); // won't print !! or Here
这篇关于当简单名称和完全限定名称发生冲突时如何引用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!