Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

java.lang.Object cannot be cast to java.lang.Class

I want to get the records from database but got an error : [Ljava.lang.Object; cannot be cast to beans.Book

The DAO Class have the following code:

List<Book> studentList=new BooksDAO().searchBook(cmbBookType.getSelectedItem().toString());
        Iterator<Book> it = studentList.iterator();

        while(it.hasNext()){
            System.out.println("Inside While_btnSearch ");
            System.out.println(it.next());
            Book book = (Book)it.next();
            System.out.println("Iterator converted to book ");
            for(int i=0;i<studentList.size();i++){
                    bookTable.setValueAt(book.getCode(), i, 0);
                    bookTable.setValueAt(book.getName(), i, 1); 
                    bookTable.setValueAt(book.getAuthor(), i, 2);
                    bookTable.setValueAt(book.getPublisher(), i, 3);
                    bookTable.setValueAt(book.getIsbn(), i, 4);
            }   

and the error log messages are here:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to beans.Book
at lms.SearchBook.btnSearchActionPerformed(SearchBook.java:286)
at lms.SearchBook.access$200(SearchBook.java:19)
at lms.SearchBook$4.actionPerformed(SearchBook.java:126)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

The searchBook() is as follows---

public List<Book> searchBook(String b_type){
    Query qr;
    Session session=SessionFact.getSessionFact().openSession();   
    qr=session.createQuery("select b.code,b.name,b.author,b.publisher,b.isbn from Book b where b.type=:bookType");
    qr.setParameter("bookType", b_type);
    System.out.println("Book Search Completed ");
    List<Book> booklist=qr.list();
    session.close();
    return booklist;

}

Please Help Me..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This mean the object you are trying to cast as book isn't a book instance, try debugging or check is instanceof before casting to confirm.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...