1

我想实现如下所示的回调功能。我的问题是如何将当前对象传递给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();
}
4

3 回答 3

2

用方法做一个接口callBack

public interface ICallBack{
    void callBack();
}

让类Foo实现这个接口。使方法startBar接受ICallBack类型参数

 publis void startBar(ICallBack callBack) {
        new Thread() {
          while (true) {
            //do something
            callBack.callback();
          }
        }.start();
      }
于 2013-04-27T14:56:01.830 回答
1

在修复了代码中的许多错别字后,它编译得很好

public interface IBar<T> {
  public void start(Foo<T> foo);
}

public class Bar<T> implements IBar<T> {

  public void start(final Foo<T> foo) {
    new Thread() {
        @Override
        public void run() {
          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); // totally possible
  }

  public T getT() {
    return baz;
  }

  public void callBack() {
    System.out.println("called back");
  }
}
于 2013-04-27T15:57:46.977 回答
0

创建 Foo inside bar 的关联。在 foo 中初始化 Bar 的时候,传递这个对象并使用它 bar.start()

public class Bar implements IBar {

Foo foo;

//setters and getters

      publis void startBar(Foo foo) {
       // use foo here
        new Thread() {
          while (true) {
            //do something
            foo.callback();
          }
        }.start();
      }

    }

现在里面 foo set foo like

bar.setFoo(this);// or u can use constructor instead of getter & setter
于 2013-04-27T14:51:46.810 回答