Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Even I'm casting Object into int, but this exception occur...

Actually my Hibernate-JPA method was return Object then I'm converting that Object into int...

Here is my Hibernate code:

@Transactional public Object getAttendanceList(User user){      Query query = entityManager.createQuery("select Count(ad) from AttendanceDemo ad inner join ad.attendee at  where at.user=:user",             Long.class);     query.setParameter("user", user);     return query.getSingleResult(); } 

Now I'm converting this Object as int:

int k = (Integer) userService.getAttendanceList(currentUser); 

I'm converting Object to Integer.

like image 891
SWEE Avatar asked Jun 18 '13 08:06

SWEE


People also ask

How do I resolve Java Lang ClassCastException error?

To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.

What is Java Lang ClassCastException?

ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.

What is ClassCastException in Java with example?

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. So, for example, when one tries to cast an Integer to a String , String is not an subclass of Integer , so a ClassCastException will be thrown.

What might a ClassCastException be?

ClassCastException is an unchecked exception that signals the code has attempted to cast a reference to a type of which it's not a subtype.


1 Answers

Use:

((Long) userService.getAttendanceList(currentUser)).intValue(); 

instead.

The .intValue() method is defined in class Number, which Long extends.

like image 122
fge Avatar answered Oct 14 '22 12:10

fge