Search code examples
javajpaeclipselink

Integer.longValue() does throw an Exception if not assigned to Number first


public Long getId()
{
    Some code ...

    TypedQuery<Long> query = entityManager.createQuery(sQuery, Long.class);
    return query.getSingleResult();
}

From this code i get a ClassCastException from Integer to Long. I checked query.getSingleResult(); in the debugger and i conatined the Integer 5.

If i change the code to query.getSingleResult().longValue(); it still does not work. I get the same Exception. But if i use

Number tmp = query.getSingleResult();
return tmp.longValue();

it works. My Question is Why doesnt the first solution work? Surley i can change my query, but i only want to know why the secound works and the first do not.

Feel free to change the title of my question. Thanks in advance!


Solution

  • Your query actually returns a Integer but you pretend that it returns a Long by calling entityManager.createQuery(sQuery, Long.class).

    Now when you execute

    query.getSingleResult()
    query.getSingleResult().longValue()
    

    the compiler inserts a cast to Long because of your generics declaration. Therefore this is actually executed:

    (Long)query.getSingleResult()
    ((Long)query.getSingleResult()).longValue()
    

    and a ClassCastException is thrown because Integer is not a Long.

    When you call

    Number tmp = query.getSingleResult();
    

    it actually performs

    Number tmp = (Number)query.getSingleResult();
    

    and this code succeeds since Integer is a Number.

    So it is not that longValue() throws an Exception but the cast that happens before.