Java泛型 - 在棘手的情况下遇到麻烦

时间:2012-02-14 01:19:41

标签: java generics

我已经在这个问题上击败了我的头几个小时了,我把它简化为一小段代码。你能看出错误的位置吗?

public class Experiment {
   class BaseMessage<Messageable> {
      Messageable once;

      BaseMessage(Messageable x) {
         once = x;
      }
   }

   class BaseEntity {
      boolean handleMessage(BaseMessage<BaseEntity> theMessage) {
         return false;
      }

   }

   class StateMachine<Thing> {
      public boolean handleMessage(BaseMessage<Thing> msg) {
         return true;
      }

   }

   class VehicleEntity extends BaseEntity {
      public StateMachine<VehicleEntity> state;

      @Override
      boolean handleMessage(BaseMessage<VehicleEntity> theMessage) {
         return state.handleMessage(theMessage);
      }
   }
}

我在这一行收到编译错误:

boolean handleMessage(BaseMessage<VehicleEntity> theMessage) {

错误是:"The method handleMessage(Experiment.BaseMessage<Experiment.VehicleEntity>) of type Experiment.VehicleEntity must override or implement a super type method"

请注意,这是我的实际代码的示例子集,以将其降低到最小值,因此代码不会做任何明智的事情。哇,如果你能想到这一点我会非常感激!

4 个答案:

答案 0 :(得分:4)

如Miserable Variable所述,在VehicleEntity handleMessage(BaseMessage<VehicleEntity> theMessage)handleMessage(BaseMessage<BaseEntity> theMessage)不是class BaseEntity<T extends BaseEntity<T>> { boolean handleMessage(BaseMessage<T> message) { ... } } class VehicleEntity extends BaseEntity<VehicleEntity> { boolean handleMessage(BaseMessage<VehicleEntity> message) { ... } } ,编译器期望后者在原始代码中。

主要的替代方案是BaseEntity采用“自”类型参数,如下所示:

{{1}}

答案 1 :(得分:1)

BaseMessage<VehicleEntity>不是BaseMessage<BaseEntity>的子类型。试试这个

abstract class BaseEntity {
    abstract <B extends BaseEntity> boolean handleMessage(BaseMessage<B> theMessage) {
        return false;
    }
}

答案 2 :(得分:0)

您希望VehicleEntity拥有仅接受handleMessage的{​​{1}}方法。

我相信这只能在Java中实现,至少它无法静态检查。但您可能需要查看Curiously recurring template pattern,看看是否可以让它适合您。

答案 3 :(得分:0)

尝试将泛型添加到类本身

   class BaseEntity<T> {
      boolean handleMessage(BaseMessage<T> theMessage) {
         return false;
      }

   }

   class VehicleEntity extends BaseEntity<VehicleEntity> {
      public StateMachine<VehicleEntity> state;

      @Override
      boolean handleMessage(BaseMessage<VehicleEntity> theMessage) {
         return state.handleMessage(theMessage);
      }
   }