我想實現一個回調函數,如下所示。我的問題是如何將當前對象傳遞給Bar.start(Foo<T> foo)
方法。 public interface IBar {public void start(Foo foo); }Java和泛型?
public class Bar<T> implements IBar<T> {
public void start(Foo<T> foo) {
new Thread() {
while (true) {
T baz = foo.getT();
//do something with the T baz object
foo.callback();
}
}.start();
}
}
public Class Foo<T> {
private T baz;
private Bar<T> bar;
public Foo(T baz, Bar<T> bar) {
this.baz = baz;
this.bar = bar;
}
public void startBar() {
bar.start(this); //---- Here I got this is not possible.
}
public T getT() {
return baz;
}
public void callBack() {
system.out.println("called back");
}
}
我想借類型T的優勢,所以我想用仿製藥。我擴展了代碼以說清楚,這裏是我的主要方法:這裏是我的主要方法:
public static void main(String[] args) {
String s = new String("one");
Integer i = new Integer(1);
Bar<String> bar1 = new Bar<String>();
Bar<Integer> bar2 = new Bar<Integer>();
Foo<String> foo1 = new Foo<String>(s, bar1);
Foo<Integer> foo2 = new Foo<Integer>(i, bar2);
foo1.startBar();
foo2.startBar();
}
難道它甚至編譯? 'Bar'不會從'IBar'執行'start'。如果你這樣做,我懷疑它會起作用。編輯:好像你修好了,這是一個錯字 – NilsH 2013-04-27 14:53:27