【问题标题】:Designing a Java Generic Hierarchy to avoid Template Class Conflict设计 Java 通用层次结构以避免模板类冲突
【发布时间】:2018-12-29 00:14:36
【问题描述】:

考虑以下 rawtype 形式的 Java 泛型类层次结构。

class A ...
class B extends A ...
class C extends A ...

使用 A 类中的方法并在 B 和 C 中重写。

String foo() ...
String bar(A a) ...

我们可以成功拨打以下电话。

String r = (new B()).foo();
String r = (new B()).bar(new C());

这里的真正目标是将 A 的实例保存在容器中 并处理它们,而不考虑我们拥有哪种 A。

A fred;
List as = new LinkedList();
for (A a : as) ... fred.bar(a); ...

B 和 C 类的对象可以毫无问题地构造并传递给 foo。 现在我们介绍泛型。

class A<T,U,V> ...
class B<T> extends A<T,Void,Object> ...
class C<N> extends A<String,Void,Object> ...

使用 A 类中的方法并在 B 和 C 中重写。

T foo() ...

然后我们进行以下合理的调用。

String r = (new A<String,Void,Object>()).foo();
String r = (new B<String>()).foo();
String r = (new C<Integer>()).foo();

String r = (new B<String>()).foo();
String r = (new B<String>()).bar(new C<Integer>());

这里的真正目标是将 A 的实例保存在容器中 并处理它们,而不考虑我们拥有哪种 A。

A<String,String,Integer> fred;
List<A<String,String,Integer>> as = new LinkedList<>();
for (A a : as) ... fred.bar(a); ...

这些决定使得无法将 B 和 C 类型的对象加载到“as”列表中, 由于通用模板中的类型冲突。

请注意,这是一个地方性的现有软件,我正在尝试清除警告。

【问题讨论】:

  • List&lt;String,String,Integer&gt; as 无效。 List 只有一个类型参数。你的意思是List&lt;A&lt;String,String,Integer&gt;&gt; as
  • @user7 是的,这就是我的意思。我可以给出具体的代码示例,但这里是实际系统的链接和示例文件。 github.com/babeloff/fql/blob/master/src/catdata/aql/exp/…

标签: java generics inheritance collections


【解决方案1】:

如果你只关心foo() 的返回值,那么你可以使用这个:

List<A<String, ?, ?>> as = ...;

这将允许您存储AA 的任何子类型,其中T 的类型参数为String,但UV 的任何内容。所以:

as.add(new A<String, String, Integer>()); // fine
as.add(new B<String>()); // fine
as.add(new C<Integer>()); // fine

as.add(new A<Double, String, Integer>()); // won't compile

但是,您将无法调用具有UV 类型参数的A 方法。如果这是一个问题,那么您似乎必须以某种方式重新设计。

可能还看到:

【讨论】:

  • 我发现提供的链接最有帮助。
猜你喜欢
  • 1970-01-01
  • 2015-05-07
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多