33

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.

3
  • Looks like getAttendanceList is returning you Long. Can you post the code for the same Commented Jun 18, 2013 at 8:29
  • Are you sure you're returning an Integer? ClassCastException says that you're not returning an Integer... Commented Jun 18, 2013 at 8:31
  • Yes.. i want to store getAttendanceList() method return value into k. then only ClassCastException coming and now i'm casting to (Integer) but again that exception come.. Commented Jun 18, 2013 at 8:34

4 Answers 4

74

Use:

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

instead.

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

Sign up to request clarification or add additional context in comments.

6 Comments

But IDE shows... The method intValue() is undefined for the type Object
Why not use ((Number) userService.getAttendanceList(currentUser)).intValue();
@johnchen902 yes, that is true... But in this case I am not sure OP really wants that. Or that the db model will change from Long to some other numeric type overnight ;)
oh... thankyou.. fge.. it's working... but when we write like ((Number) userService.getAttendanceList(currentUser)).intValue(); it is not working why???
@user2496295 uh! That should work... Or do you have another Number class which is not the JDK's?
|
6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

Comments

0

You can do like that :

int k = Math.toIntExact((Long) userService.getAttendanceList(currentUser));

Comments

0

Just change the long to Number Remember your database is Number not int or long.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.