利用介面解決Java工程間循環參考而報錯的問題

來源:互聯網
上載者:User

解決Eclipse中Java工程間循環參考而報錯的問題

 如果我們的項目包含多個工程(project),而它們之間又是循環參考的關係,
 那麼Eclipse在編譯時間會拋出如下一個錯誤資訊:
 “A cycle was detected in the build path of project: XXX”
解決方案非常簡單:
 Eclipse Menu -> Window -> Preferences... ->
  Java -> Compiler -> Building -> Building path problems -> Circular dependencies ->

 將Error改成Warning。

 

但是在Android中

發現循環參考後不能正常build了,找不到Android的apk,所以不適用,尋求另一種方法如下:

利用介面產生副本回調的方法就好,這樣可以避免循環參考,也許可以認為介面是那個執行個體的一份副本

 

建立介面回調
 *   1.建立一個介面讓Test2實現,相當於Test2的一份副本
 *   2.在Test2中通過setTest2duplicate(Test2duplicate test)方法傳遞給Test一個執行個體
 *   3.運行Test2的main方法,調用Test的方法,接著在Test的方法中就可以調用回Test2的方法了

Test.java

public class Test {//建立一個Test2的執行個體public static Test2duplicate test2 = null;//提供設定Test2執行個體的方法public static  void setTest2duplicate(Test2duplicate test){System.out.println("擷取到一個test2");test2 = test;}public static void sayHello(){System.out.println("Hi,this is Test!not Test2...");if (test2 !=null) {test2.sayHello2();}else {System.out.println("test2 is null!");}}

Test2.java

/** * @author Juhn.Xu * 2012-8-20 * <p> * 先調用Test的方法,再回調自己的方法 * </p> */public class Test2 implements Test2duplicate{public Test2() {}public static void main(String[] args) {//先運行Test的方法,此時未傳遞Test2的執行個體Test.sayHello();//傳遞一個Test2的執行個體給 TestTest.setTest2duplicate(new Test2());//再運行Test的方法Test.sayHello();}public void sayHello2(){System.out.println("Hi,this is Test2");}}

Test2duplicate.java

/** * @author Juhn.Xu * 2012-8-20 * <p> * 作為Test2的一個副本,提供Test2的sayHello2()方法 */public interface Test2duplicate {public void sayHello2();}

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.