我想实现如下所示的回调功能。我的问题是如何将当前对象传递给Bar.start(Foo<T> foo)
方法。公共接口 IBar { public void start(Foo foo); }
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();
}