递归泛型类型列表

3

我有一个通用接口,需要将其类型作为通用参数:

interface Base<X extends Base<X>> {
    X foo();
}
class Derived implements Base<Derived> {
    public Derived foo() { ... }
    public Derived bar() { ... }
}
class Derived2 implements Base<Derived2> {
    public Derived2 foo() { ... }
    public void quz() { ... }
}

我有另一个类,它将此接口用作通用参数。

interface Policy<B extends Base<B>> {
  B apply(B b);
}

我有一些只能与特定派生类一起使用的策略实现:

class DerivedPolicy implements Policy<Derived> {
   public Derived apply(Derived d) {
     return d.foo().bar();
   }
}

但是还有其他一些可以与任何实现一起使用的工具。
class GeneralPolicy implements Policy {
     public Base apply(Base b) {
         return b.foo();
     }
}

上述代码可以编译,但是会在GeneralPolicy中出现未经检查的类型警告,这是准确的,因为Base没有指定其泛型类型。第一个明显的修复方法是GeneralPolicy实现Policy<Base>,w

Test.java:26: error: type argument Base is not within bounds of type-variable B
class GeneralPolicy implements Policy<Base> {
                                      ^
  where B is a type-variable:
    B extends Base<B> declared in interface Policy

使用GeneralPolicy implements Policy<Base<?>>也不起作用:

Test.java:26: error: type argument Base<?> is not within bounds of type-variable B
class GeneralPolicy implements Policy<Base<?>> {
                                          ^
  where B is a type-variable:
    B extends Base<B> declared in interface Policy

我做了最后一次尝试:GeneralPolicy实现了Policy<Base<? extends Base<?>>>
Test.java:26: error: type argument Base<? extends Base<?>> is not within bounds of type-variable B
class GeneralPolicy implements Policy<Base<? extends Base<?->- {
                                           ^
  where B is a type-variable:
    B extends Base<B> declared in interface Policy

有没有一种方法可以声明它,既能正常工作又不会有未检查的类型?

我非常确定这个问题可以用更简单易懂的方式来表达 :) - Eduardo Dennis
我认为你可能需要重新考虑解决这个问题的更广泛方法,因为我的直觉告诉我可能有一个更简单的解决方案,不会破坏泛型。 - Joe C
1个回答

0
在Java 5+中,返回类型可以是协变的,因此您不需要使用泛型,在开头您有:
interface Base {
    Base foo();
}
class Derived implements Base {
    public Derived foo() { ... }
    public Derived bar() { ... }
}

那么,我再也不会看到关于泛型的问题了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接