Analysis and Solutions for ClassCastException from Long to Integer in Java

Dec 11, 2025 · Programming · 10 views · 7.8

Keywords: Java | Type Conversion | Hibernate

Abstract: This article delves into the common java.lang.ClassCastException in Java 1.6, particularly when attempting to cast a Long object to Integer. Through a typical Hibernate query scenario returning Object type data, it explains the root cause of the conversion failure and provides a correct solution using the intValue() method from the Number class. Additionally, it discusses best practices for type-safe programming, including the use of generics, considerations for autoboxing/unboxing, and how to avoid similar runtime exceptions.

Problem Background and Exception Analysis

In Java programming, type conversion is a common operation, but improper casting can lead to runtime exceptions. The case discussed here involves a typical Hibernate query scenario: a method returns an Object type, and the developer attempts to convert it to int or Integer. The original code is shown below, where the query uses Long.class as the result type but is treated as Object upon return:

@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();
}

On the caller side, the developer tries a cast:

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

This results in a java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer exception. The root cause is that the Hibernate query specifies Long.class, so it returns a Long object, and Long and Integer, while both subclasses of Number, cannot be directly cast in Java as they are distinct classes.

Core Solution

According to the best answer, the correct approach is to use the intValue() method provided by the Number class. Since Long inherits from Number, this method can be called directly to convert the Long value to an int primitive type. Example code:

int k = ((Long) userService.getAttendanceList(currentUser)).intValue();

This method avoids the ClassCastException because it does not attempt to change the object's type but retrieves the value through a method call. Semantically, this aligns better with type-safe principles, as intValue() returns an int primitive; if an Integer object is needed, autoboxing can be applied further.

In-Depth Understanding of Type Conversion Mechanisms

Type conversion in Java is divided into two categories: primitive type conversion and reference type conversion. Primitive type conversion (e.g., long to int) may lose precision but typically does not throw exceptions; reference type conversion (e.g., Long to Integer) is constrained by inheritance relationships. Long and Integer have no direct inheritance, so casting fails. Additionally, autoboxing and unboxing mechanisms can cause confusion in such scenarios, e.g., direct assignment int k = (Long) obj; leads to a compilation error because Java does not allow implicit unboxing from Long to int.

Best Practices and Extended Discussion

To prevent such exceptions, it is recommended to use generics in Hibernate queries to specify the return type directly, for example:

Query<Long> query = entityManager.createQuery("select Count(ad) from AttendanceDemo ad inner join ad.attendee at  where at.user=:user", Long.class);
Long result = query.getSingleResult();
int k = result.intValue();

This enhances code type safety and readability. Other supplementary solutions include using the intValue() method from Number (as mentioned) or checking the object type before conversion. In more complex scenarios, if the query might return null, null checks should be added to prevent NullPointerException. The article also discusses the essential difference between HTML tags like <br> and characters, emphasizing the need to escape special characters in textual descriptions to maintain DOM integrity.

In summary, proper handling of type conversion requires an understanding of Java's type system and Hibernate's return mechanisms. By using methods like intValue(), developers can avoid runtime exceptions and write more robust code.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.