【发布时间】: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