Erh*_*nis 5 java generics types
I've seen a number of similar questions, but I don't think any were quite isomorphic, and none quite answered my question.
Suppose there are two interfaces, Tree
and Named
. Suppose further that I am given a method whose signature is
public <T extends Tree & Named> T getNamedTree();
How can I save the returned value to a variable, while still retaining the information that it implements both Tree
and Named
? I can't find a way of declaring a variable like
public <T extends Tree & Named> T mNamedTree;
并尝试将其转换为扩展的接口Tree
并Named
导致类转换异常。
变量必须具有什么范围?
这里存在三种可能性。
A) 该变量只是一个局部变量。在这种情况下,您几乎已经有了答案...您只需要为该类型的封闭方法声明一个类型参数:
interface ItfA { Number propA(); };
interface ItfB { Number propB(); };
class Main {
private <T extends ItfA & ItfB> T getT() {
return null;
}
private <TT extends ItfA & ItfB> void doStuffWithT() {
TT theT = getT();
System.err.println(theT.propA());
System.err.println(theT.propB());
}
}
Run Code Online (Sandbox Code Playgroud)
B) 范围是对象的生命周期,在这种情况下是成员字段。显而易见的答案是使类成为通用类,并且类型参数将具有相同的&
约束:
interface ItfA { Number propA(); };
interface ItfB { Number propB(); };
class Main<T extends ItfA & ItfB> {
T theT;
public void setT(T newT) {
theT = newT;
}
public void doStuffWithT() {
System.err.println(theT.propA());
System.err.println(theT.propB());
}
}
Run Code Online (Sandbox Code Playgroud)
C) 作用域是程序的生存期,那么该变量就是静态类成员。这里你没有泛型解决方案。
C.1)显然,如果您要处理的值的类已知,您将只使用该类作为字段类型。
C.2) 如果不是,您可以限制代码仅处理实现扩展 ItfA 和 ItfB 的接口的类。那个界面,比如说ItfAB
。将是字段类型。
C.3) 现在,不施加该约束怎么样?允许代码处理来自实现这些接口的任何类的对象怎么样?
不幸的是,没有一个明确的解决方案:
C.3.a) 您可以键入该字段Object
并提供以 ItfA 或 ItfB 形式访问它的方法(基本上隐藏转换)。
C.3.b) 或者,您不直接保存对对象的引用,而是使用实现这些接口的代理对象,并将对这些接口方法的调用委托给原始的“”T
类型值。该代理的类本身可以是接受任意值的泛型<T extends ItfA & ItfB>
(类似于上面的 B. 示例)。