在JSF中实现购物篮时获取java.lang.ClassCastException

时间:2015-08-12 11:27:25

标签: java jsf

我有篮子问题。如何解决这类问题呢?

  

引起:java.lang.ClassCastException:   pl.library.web.books.cdi.CartBean $ Proxy $ _ $$ _ WeldClientProxy不能   强制转换为java.util.List

@Named
@SessionScoped
public class CartBean implements Serializable {

    private BookLDM book;
    private int quantity;

    public CartBean(BookLDM byId, int i) {
        this.book = byId;
        this.quantity = i;
    }

    public BookLDM getBook() {
        return book;
    }

    public void setBook(BookLDM book) {
        this.book = book;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public CartBean() {}
}
@Named
@RequestScoped
public class BoxManager implements Serializable {

    private static final long serialVersionUID = 8267670504661589685L;

    @Inject
    private CartBean cart;
    @EJB
    private BookService bookService;

    public BoxManager() {}

    public CartBean getCart() {
        return cart;
    }

    public void addItem(final Long itemId) {

        if (cart == null) {
            List<CartBean> cart = new ArrayList<CartBean>();
            cart.add(new CartBean(this.bookService.getById(itemId), 1));
        } else {
            List<CartBean> cart = (List<CartBean>) getCart();
            int index = isExisting(itemId);
            if (index == -1) {
                cart.add(new CartBean(this.bookService.getById(itemId), 1));
            } else {
                int quantity = cart.get(index).getQuantity() + 1;
                cart.get(index).setQuantity(quantity);
            }
        }
    }

    private int isExisting(long id) {
        List<CartBean> cart = (List<CartBean>) getCart();

        for (int i = 0; i < cart.size(); i++) {
            if (cart.get(i).getBook().getId() == id) {
                return i;
            }
        }

        return -1;
    }
}

1 个答案:

答案 0 :(得分:0)

信息很明显。在这一行[{1}}中,您试图将List<CartBean> cart = (List<CartBean>) getCart();投射到CartBean。它不能工作。这样做与上面几行相同,首先创建新的List<CartBean>,然后创建ArrayList<CartBean>方法返回的新对象,最后将此对象添加到列表中。