olgacosta
olgacosta

Reputation: 1138

Error in casting Object[] to byte[]

I want to read from database a pdf, which stores as BLOB and I want to get List<bytes[]>

session.beginTransaction();
final Criteria criteria = session.createCriteria(MyClass.class);
criteria.add(Restrictions.eq("id",id));
final ProjectionList projectionList = Projections.projectionList().add(
        Projections.property("bdoc"));
criteria.setProjection(projectionList);
List<Object[]> list = criteria.list();
List<byte[]> listBytes = new ArrayList<byte[]>();
for (Object[] item : list) {
    listBytes.add((byte[]) item[0]);
}
session.getTransaction().commit();

But I get an error in this line for (Object[] item : list) {

[ERROR] [B cannot be cast to [Ljava.lang.Object;

I've debugged and I do read data from database: my List<Object[]> list = criteria.list() is not empty. But I can not convert from List<Object[]> to List<bytes[]>. What am I doing wrong? Help me please to resolve my problem.

Upvotes: 2

Views: 1670

Answers (2)

Duncan Jones
Duncan Jones

Reputation: 69369

This problem is caused because Criteria.list() returns a raw List. As a result, you are able to write code that causes a ClassCastException. With a properly typed list, the compiler would prevent this.

As explained in the other answer, the text [B cannot be cast to [Ljava.lang.Object means that a byte[] is being cast to an Object[], which is not allowed.

This means that your list contains byte[] objects and you should declare it as such:

List<byte[]> list = criteria.list();

In addition, the contents of your for-loop now look incorrect:

listBytes.add((byte[]) item[0]);

Since item is now a byte[], it's not correct to cast a byte to a byte[]. Perhaps you need to remove the array index [0].

Upvotes: 0

SMA
SMA

Reputation: 37063

B cannot be cast to [Ljava.lang.Object;

Means you are indeed getting bytearray and you are trying to convert it into Object array.

Upvotes: 3

Related Questions