【问题标题】:Java override abstract generic methodJava 重写抽象泛型方法
【发布时间】:2011-07-05 16:46:11
【问题描述】:

我有以下代码

public abstract class Event {
    public void fire(Object... args) {
        // tell the event handler that if there are free resources it should call 
        // doEventStuff(args)
    }

    // this is not correct, but I basically want to be able to define a generic 
    // return type and be able to pass generic arguments. (T... args) would also 
    // be ok
    public abstract <T, V> V doEventStuff(T args);
}

public class A extends Event {
   // This is what I want to do
   @Overide
   public String doEventStuff(String str) {
      if(str == "foo") { 
         return "bar";
      } else {
         return "fail";
      }
   }
}

somewhere() {
  EventHandler eh = new EventHandler();
  Event a = new A();
  eh.add(a);
  System.out.println(a.fire("foo")); //output is bar
}

但是我不知道该怎么做,因为我不能用特定的东西覆盖doEventStuff

有人知道怎么做吗?

【问题讨论】:

  • 由于泛型参数不出现在任何其他地方,方法签名大致等价于public abstract Object doEventStuff(Object args)。这是一个将anything 作为参数并返回something 的方法。你确定这是你想要的吗?如果没有,您可能希望在 Event 类上定义 T 和/或 V 参数,而不仅仅是方法。
  • 另外,请注意if(str == "foo") { 可能是错误的,您需要if("foo".equals(str)) { 之类的东西
  • 感谢 "foo".equals... 如果没有引起注意,这会搞砸很多事情。

标签: java generics abstract-class custom-attributes


【解决方案1】:

不清楚您要做什么,但也许您只需要使Event 本身具有通用性:

public abstract class Event<T, V>
{
    public abstract V doEventStuff(T args);
}

public class A extends Event<String, String>
{
    @Override public String doEventStuff(String str)
    {
        ...
    }
}

【讨论】:

  • 这就是我想做的:)。这真的比我想象的要容易。非常感谢。
【解决方案2】:

您正在使用泛型,但您没有提供绑定。

public abstract class Event<I, O> { // <-- I is input O is Output
  public abstract O doEventStuff(I args);
}

public class A extends Event<String, String> { // <-- binding in the impl.
  @Override
    public String doEventStuff(String str) {
  }
}

或者更简单的只有一个通用绑定...

public abstract class Event<T> { // <-- only one provided
  public abstract T doEventStuff(T args);
}

public class A extends Event<String> { // <-- binding the impl.

  @Override
    public String doEventStuff(String str) {
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2013-01-02
    • 1970-01-01
    • 2018-07-05
    • 2019-10-10
    • 1970-01-01
    相关资源
    最近更新 更多