现在的位置: 首页 > 综合 > 正文

利用接口解决Java工程间循环引用而报错的问题

2012年03月13日 ⁄ 综合 ⁄ 共 1375字 ⁄ 字号 评论关闭

解决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的实例给 Test
		Test.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();
}

 

 

抱歉!评论已关闭.