JAVA相同接口类的强制转换有关问题
JAVA相同接口类的强制转换问题
接口文件:Itest.java
package comm; public interface Itest { public String getStrTemp(); public void setStrTemp(String strTemp); }
Test.java
package comm; public class Test implements Itest { public String strTemp; public String getStrTemp() { return strTemp; } public void setStrTemp(String strTemp) { this.strTemp = strTemp; } }
Test1.java
package comm; public class Test implements Itest { public String strTemp; public String getStrTemp() { return strTemp; } public void setStrTemp(String strTemp) { this.strTemp = strTemp; } }
运行代码
public static void main(String[] args) { Itest t = new Test(); t.setStrTemp("test"); System.out.println(t); Itest t1 = (Test1) t; System.out.println(t1.getStrTemp()); }
正常提示错误:java.lang.ClassCastException
请问有没有办法实现 Test 和 Test1 之间的互相转换
1 楼
rasonyang
2008-06-06
只能用BeanUtils或者CGLIB的copy方法。
2 楼
Julysea
2008-06-06
Itest t1 = (Test1) t; 一句中t已经是Itest的实例,假设可以执行,也属多余。
单就Test和Test1的互换可以适用适配器模式来做
单就Test和Test1的互换可以适用适配器模式来做