2013-04-27 104 views
1

我想實現一個回調函數,如下所示。我的問題是如何將當前對象傳遞給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(); 
} 
+0

難道它甚至編譯? 'Bar'不會從'IBar'執行'start'。如果你這樣做,我懷疑它會起作用。編輯:好像你修好了,這是一個錯字 – NilsH 2013-04-27 14:53:27

回答

1

的參數在你的代碼固定無數錯別字後,compiled fine

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"); 
    } 
} 
+0

你有權利,謝謝。我在代碼中發現了錯誤。 – user1534880 2013-04-27 16:16:34

0

創建一個Foo裏面的關聯吧。在初始化中富酒吧的時候,通過這個對象,並用它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(); 
     } 

    } 

現在富富集裏面像

bar.setFoo(this);// or u can use constructor instead of getter & setter 
2

請與方法callBack的接口。

public interface ICallBack{ 
    void callBack(); 
} 

使類Foo執行此接口。製作方法startBar接受ICallBack

publis void startBar(ICallBack callBack) { 
     new Thread() { 
      while (true) { 
      //do something 
      callBack.callback(); 
      } 
     }.start(); 
     } 
+0

'界面'更適合你的要求 – Apurv 2013-04-27 15:42:14