프로젝트를 하면서 이런 걸 올리고 싶었는데 하는 도중에는 정말 여유가 없었다ㅎㅎ 내가 너무 못하는 것만 같아서 새벽 5시까지 하고 해결해놓고 자고 하느라고ㅠㅠ 그래도 나도 열심히 했고 다른 분들도 열심히 해주시고, 오류를 잘 고치시는 분이 계셔서 가끔 찾아가서 여쭤봐서 나름 빨리 해결했다!!
교육할때 퇴실큐알을 꼭 찍고 퇴실을 해야하는데, 그것도 잊을만큼 여유가 없어서 결석이 억울하게 하나 생길정도로 여유가 없긴 했지만ㅋㅋㅋㅋ 그래도 틈틈히 코드는 복사를 해둬서 조금이라도 해뒀으니 다음 프로젝트 전까지는 다 올려야겠다.
ClassCastException
식당에서 음식메뉴를 선택하고 결제하기를 누르면 Order객체로 주문날짜, 음식점명, 메뉴명 등등 여러가지 값을 "order_list.txt"파일에 저장하고, 주문내역 출력을 할때 내가 그 값을 들고오기 위해 파일 입력을 해주는 과정에서 classCastException이 발생했다!
ArrayList의 메소드인 addAll( )은 컬렉션 타입 객체 전체를 arraylist에 추가시켜주는 메소드이다.
그런데 앞에서 "order_list.txt" 파일에는 Order객체로 값을 저장한다.
따라서 파일에 들어있는 값은 Order인데 totalorderList.addAll((ArrayList<Order>)ois.readObject()); 로 Order로 저장된 값을 ArrayList<Order>로 변환하려고 해서 안된다고 ClassCastException이 떴었다,,,ㅎㅎㅎ
앞으로는 이거는 틀리지 않고 잘해야지!ㅎㅎ
1. 문제코드
public class OrderListDao {
private ArrayList<Order> totalorderList = new ArrayList<Order>();
private ArrayList<Order> userOrderList = new ArrayList<Order>();
private ArrayList<Order> otherOrderList = new ArrayList<Order>();
private Member m;
public OrderListDao() {
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("order_list.txt"))){
totalorderList.addAll((ArrayList<Order>)ois.readObject()); //주문내역담긴 파일 전체 orderlist에 담기
String userID = MainFrame.loginUserId;
for(Order ol : totalorderList) {
if(ol.getUserId().equals(userID)) { //userid와 orderList에 있는 userid비교
userOrderList.add(ol); //아이디 같으면 새로운 orderList에 담기
}else {
otherOrderList.add(ol);
}
}
}catch(EOFException e) {
return;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
userOrderList = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(NullPointerException e) { //갑자기 nullpointerexception나서 추가함
userOrderList = null;
}
}
2. 해결코드
그리고 위와 다른점이 하나 더 있는데 위에서는 생성자에서 바로 값을 불러왔지만 이부분을 새로운 메소드 loadOrderList()로 빼서 불러올 일이 있는 경우에만 불러올 수 있도록 하였다. 나는 주문목록이어서 사실 언제나 값을 불러오니 생성자로 쓰는게 좋다고 생각했는데 OrderListDao객체가 생성되거나 할때마다 값을 불러오는 것보다는 따로 빼는게 더 좋다고 하셔서 이렇게 바꿨다. 이렇게 바꿈으로써 다른 메소드를 호출할때 loadORderList()를 같이 호출하였다.
public void loadOrderList() {
totalorderList = new ArrayList<Order>();
userOrderList = new ArrayList<Order>();
otherOrderList = new ArrayList<Order>();
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("order_list.txt"))) {
userID = MainFrame.loginUserId;
Order o;
while ((o = (Order) ois.readObject()) != null) {
totalorderList.add(o);
if (o.getBasket().getUserId().equals(userID)) { //여기서 for문 안된다!!
userOrderList.add(o);
} else
otherOrderList.add(o);
}
} catch (EOFException e) {
return;
} catch (FileNotFoundException e) {
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) { // 갑자기 nullpointerexception나서 추가함
return;
}
}
java.io.StreamCorruptedException: invalid type code: AC
이거는 여러군데서 찾아봤는데 정확히는 이해하지 못했다,,,
영어로 적힌 글도 봤는데 한번 더 알아봐야지 일단 내가 알아본 바로는 2개의 스트림이 생성되어서 그렇다고 했다!
그래서 새로운 스트림을 생성해주는 것이 해결책이라고 까지 찾았다.
같은 조원분 말씀으로는 Order클래스가 Basket을 상속을 해서 Basket객체의 필드까지 사용을 하는데
저장될때도 Basket.필드명으로 저장되기 때문이라고 하셨다!
그래서 Order도 읽고 Basket도 읽으려고 하기때문에 나는 오류라고 하셔서 일단 첫번째로 상속을 없애고, Order클래스에 필드로 Basket클래스를 넣고 Order.getBasket.getPrice 이런식으로 쓰니 해결할 수 있었다!!!
처음에 이 오류를 보고 얼마나 당황했는지ㅠㅠㅠㅠ 그래도 빠르게 해결이 되어서 좋았지만 stream에서 header가 뭔지 body가 뭔지 이런거랑 저 에러에 대해 좀더 알아봐야 할 것 같다. 이해는 되었지만 그래도 아쉽다.
1. 문제코드
public class OrderListDao {
private ArrayList<Order> totalorderList = new ArrayList<Order>();
private ArrayList<Order> userOrderList = new ArrayList<Order>();
private ArrayList<Order> otherOrderList = new ArrayList<Order>();
private String userID;
public OrderListDao() {
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("order_list.txt"))){
while(true) {
totalorderList.add((Order)ois.readObject());
}
}catch(EOFException e) {
return;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
userOrderList = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(NullPointerException e) { //갑자기 nullpointerexception나서 추가함
userOrderList = null;
}
}
2. 해결 후 사용
아래와 같이 상속관계를 없애버리고 Order클래스에 Basket클래스를 필드로 넣었다.
나라면 이렇게 빠르게 해결을 못했을텐데 팀원분 덕분에 이런방법도 있구나 하고 배워서 꼭 기억해두고 싶다.
내가 후에 쓰지는 않더라도 알아볼 수는 있겠지!!
public class Order implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Basket basket;
private int payment;
private String request;
private Calendar orderedDate;
private String userAddress;
private boolean orderState;
private int sNum;
o.getBasket().getUserId().equals(userID)
이렇게 order클래스에서 getbasket을 하고 id를 가져온다!
원래는 상속이어서 o.getUserId()였는데 말이다.
public OrderListDao() {
totalorderList = new ArrayList<Order>();
userOrderList = new ArrayList<Order>();
otherOrderList = new ArrayList<Order>();
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("order_list.txt"))) {
userID = MainFrame.loginUserId;
Order o;
while ((o = (Order) ois.readObject()) != null) {
totalorderList.add(o);
if (o.getBasket().getUserId().equals(userID)) { //여기서 for문 안된다!!
userOrderList.add(o);
} else
otherOrderList.add(o);
}
} catch (EOFException e) {
return;
} catch (FileNotFoundException e) {
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NullPointerException e) { // 갑자기 nullpointerexception나서 추가함
return;
}
}
'Java > 프로젝트' 카테고리의 다른 글
[세미프로젝트] 시연, 코드리뷰 (0) | 2021.09.24 |
---|---|
[세미] DB 연동_테이블 분할 고민중 (0) | 2021.09.06 |
[미니프로젝트] 미니프로젝트 끝! (2) | 2021.06.16 |