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
.
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.
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.
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.
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.
Use:
((Long) userService.getAttendanceList(currentUser)).intValue();
instead.
The .intValue()
method is defined in class Number
, which Long
extends.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With