我正在尝试修改从方法作为对象集合返回的特定对象。现在许多其他对象也被添加到这个集合中。因此,找到特定对象变得困难。我尝试使用“instanceof”解决它,但出现以下异常:
java.lang.ClassCastException: com.sheesoft.MockBean cannot be cast to com.sheesoft.TestBean
at com.sheesoft.Main.main(Main.java:30)
我已经能够用一些测试类重现相同的异常。请让我知道我哪里出错了。
主要的:
package com.sheesoft;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Collection<Object> beanCollection = new ArrayList<Object>();
TestBean tb1 = new TestBean();
MockBean mb1 = new MockBean();
beanCollection.add(tb1);
beanCollection.add(mb1);
try{
Iterator<Object> itr = beanCollection.iterator();
while(itr.hasNext()){
Object object = itr.next();
if(object instanceof TestBean){
TestBean tb2 = (TestBean) itr.next();
tb2 = modifyTestBody(tb2);
System.out.println(tb2.getBody());
}
if(object instanceof MockBean){
MockBean mb2 = (MockBean) itr.next();
System.out.println(mb2.getMockPayload());
}
}
}catch(Exception e){
e.printStackTrace();
}
}
private static TestBean modifyTestBody(TestBean tb) {
tb.setBody("NewBody");
return tb;
}
}
豆1:
package com.sheesoft;
public class TestBean {
private String header;
private String body;
public TestBean(){
setHeader("header");
setBody("body");
}
public String getHeader(){
return header;
}
public String getBody(){
return body;
}
public void setHeader(String header){
this.header=header;
}
public void setBody(String body){
this.body = body;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("header = "+header+"\n");
sb.append("body = "+body+"\n");
String returns = sb.toString();
return returns;
}
}
豆2:
package com.sheesoft;
public class MockBean {
private String mockHeader;
private String mockBody;
private String mockPayload;
public MockBean(){
setMockHeader("mockHeader");
setMockBody("mockBody");
setMockPayload("mockPayload");
}
public String getMockHeader(){
return mockHeader;
}
public String getMockBody(){
return mockBody;
}
public String getMockPayload(){
return mockPayload;
}
public void setMockHeader(String header){
this.mockHeader=header;
}
public void setMockBody(String body){
this.mockBody = body;
}
public void setMockPayload(String payload) {
this.mockPayload = payload;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("mockHeader = "+mockHeader+"\n");
sb.append("mockBody = "+mockBody+"\n");
sb.append("mockPayload"+mockPayload+"\n");
String returns = sb.toString();
return returns;
}
}