iui*_*uiz 8 java generics abstract-class custom-attributes
我有以下代码
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
}
Run Code Online (Sandbox Code Playgroud)
但是我不知道怎么做,因为我不能doEventStuff用特定的东西覆盖.
有谁知道如何做到这一点?
Jon*_*eet 18
你要做的事情并不是很清楚,但也许你只需要让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)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
您使用的是泛型,但是您没有提供绑定.
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) {
}
}
Run Code Online (Sandbox Code Playgroud)
或者只使用一个通用绑定更简单...
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) {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17703 次 |
| 最近记录: |