- java.lang.ClassCastException: класс java.lang.Integer не может быть приведен к классу java.lang.Long
- Решение
- Рекомендации
- How to Fix ClassCastException «java.lang.Integer cannot be cast to class java.lang.Long»
- 1. Using Number casts
- 2. Using instanceof
- 3. Using toString()
- How to Fix ‘class java.lang.Integer cannot be cast to class java.lang.Long’ Error in Java
- Reasons for the error
- Issue with loading CartItem, handling Number subclasses, or reading a Parquet file
- Improper typecasting
- Issue with no join column defined in a book or when handling BigInteger objects
- Issue in JPA
- Fixing the error
- Usage of Integer.valueOf()
- Usage of String.valueOf()
- Usage of generics while using Collections
- Usage of BigInteger.longValue() or BigInteger.intValue()
- Best practices
- Naming conventions
- Proper indentation
- Clear and concise code
- Auto-boxing and auto-unboxing features in Java
- Debugging Java code
- Debugging tools
- Printing out variable values
- Checking log files
- Java libraries and frameworks
- Spring
- Hibernate
- Apache Struts
- Other helpful code examples for fixing the ‘class java.lang.Integer cannot be cast to class java.lang.Long’ error in Java
- Conclusion
- Frequently Asked Questions — FAQs
- What is the cause of the «class java.lang.Integer cannot be cast to class java.lang.Long» error in Java?
- How can I fix the «class java.lang.Integer cannot be cast to class java.lang.Long» error in Java?
- What are some best practices to prevent the «class java.lang.Integer cannot be cast to class java.lang.Long» error in Java?
- What are some debugging tips for Java code related to the «class java.lang.Integer cannot be cast to class java.lang.Long» error?
- What Java libraries and frameworks can help to prevent the «class java.lang.Integer cannot be cast to class java.lang.Long» error?
- How can I prevent typecasting errors in Java with Integer and Long classes?
java.lang.ClassCastException: класс java.lang.Integer не может быть приведен к классу java.lang.Long
Ниже приведен пример jdbcTemplate.queryForList возвращает объект Integer и мы пытаемся превратить его в Long непосредственно:
public List findAll() < String sql = "SELECT * FROM CUSTOMER"; Listcustomers = new ArrayList<>(); List> rows = jdbcTemplate.queryForList(sql); for (Map row : rows) < Customer obj = new Customer(); obj.setID(((Long) row.get("ID"))); // объект является целым числом obj.setName((String) row.get("NAME")); customers.add(obj); >return customers; >
Caused by: java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap') at com.csharpcoderr.misc.CustomerRepository.findAll(CustomerRepository.java:73) at com.csharpcoderr.misc.CustomerRepository$$FastClassBySpringCGLIB$$7fc6ff36.invoke() at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) at com.csharpcoderr.misc.CustomerRepository$$EnhancerBySpringCGLIB$$f96f7027.findAll() at com.csharpcoderr.StartApplication.startCustomerApp(StartApplication.java:103) at com.csharpcoderr.StartApplication.run(StartApplication.java:72) at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813)
Решение
Чтобы решить это, преобразовать его обратно в оригинал Integer и бросить его Long
obj.setID(((Integer) row.get("ID")).longValue()); //obj.setID(((Long) row.get ("ID")));
Integer num = 1; Long numInLong = num.longValue(); // целое число в длинное Long numInLong2 = Long.valueOf(num); // целое число в длинное
Рекомендации
How to Fix ClassCastException «java.lang.Integer cannot be cast to class java.lang.Long»
Trying to cast an Object may throw a ClassCastException .
Object obj = 1; long longVal = (long) obj;
The error stack trace will look something like this:
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader 'bootstrap')
The same error can be found with any pair of types: java.lang.Double cannot be cast to java.lang.Integer .
1. Using Number casts
When it comes to handling Number subclasses (e.g. Integer , Long ), we don’t need to rely on the auto-unboxing (i.e. the automatic conversion between the primitive types and their corresponding object wrapper classes).
It’s safe to cast the value to Number and call the appropriate method to obtain the value (e.g. intValue() , longValue() ).
Object obj = 1; long longVal = ((Number) obj).longValue();
Object obj = 1L; int intVal = ((Number) obj).intValue();
The downside to this solution is that it will silently continue if obj is a floating point number or double, a scenario in which we’d prefer an exception to be thrown.
2. Using instanceof
We can also just use instanceOf to check for the appropriate type.
Object obj = 1; if (obj instanceof Integer) int intVal = ((Integer) obj).intValue(); > else if (obj instanceof Long) long longVal = ((Long) obj).longValue(); >
3. Using toString()
We can also cast to a String and pass it into valueOf() .
Object obj = 1; long longVal = Long.valueOf(obj.toString());
How to Fix ‘class java.lang.Integer cannot be cast to class java.lang.Long’ Error in Java
Learn how to fix the common Java error of «class java.lang.Integer cannot be cast to class java.lang.Long». Find out the reasons for the error, best practices to prevent it, and how to debug Java code.
Java is a popular programming language used for developing various applications, but sometimes developers encounter errors while working with Java code. One common error is “ class java.lang.integer cannot be cast to class java.lang.long ”. This error occurs when there is an attempt to cast an Integer object to a Long object or vice versa in Java. In this blog post, we will discuss the reasons for this error and how to fix it.
Reasons for the error
The “class java.lang.Integer cannot be cast to class java.lang.Long” error can occur due to various reasons, such as:
Issue with loading CartItem, handling Number subclasses, or reading a Parquet file
When loading CartItem, this error can occur due to the usage of the wrong data type for the quantity attribute. Similarly, when handling Number subclasses, this error can occur due to the usage of the wrong data type for the value attribute. When reading a Parquet file, this error can occur due to the usage of the wrong data type for the column.
Improper typecasting
Improper typecasting can also cause this error, such as when attempting to cast a Double object to a String or when casting an Integer object to a Byte.
Issue with no join column defined in a book or when handling BigInteger objects
The error can also occur when there is no join column defined in a book or when handling BigInteger objects.
Issue in JPA
In JPA, this error can occur due to the usage of the wrong data type.
Fixing the error
To fix this error, one should either use Integer.valueOf() or convert the Long object to a string using String.valueOf(). Using generics while using Collections can also prevent ClassCastException. If the error occurs due to the usage of the wrong data type, changing the data type to the correct one can fix the error.
Usage of Integer.valueOf()
Integer.valueOf() returns an Integer object that represents the specified int value.
Usage of String.valueOf()
String.valueOf() returns a string representation of the Long object.
Usage of generics while using Collections
Using generics while using Collections ensures that only objects of a certain data type can be added to the collection.
Usage of BigInteger.longValue() or BigInteger.intValue()
When handling BigInteger objects, using BigInteger.longValue() or BigInteger.intValue() can prevent this error from occurring.
Best practices
Following naming conventions, using proper indentation, and writing clear and concise code can prevent this error from occurring. Using auto-boxing and auto-unboxing features in Java can also prevent this error.
Naming conventions
Naming conventions help to make the code more readable and understandable.
Proper indentation
Proper indentation makes the code more organized and easier to read.
Clear and concise code
Clear and concise code helps to reduce errors and makes the code easier to maintain.
Auto-boxing and auto-unboxing features in Java
Auto-boxing and auto-unboxing features in Java convert primitive data types into objects and vice versa, simplifying the coding process.
Debugging Java code
tips for debugging java code include using debugging tools, printing out variable values, and checking log files.
Debugging tools
Debugging tools such as Eclipse and NetBeans can help to identify errors in Java code.
Printing out variable values
Printing out variable values can help to identify where the error occurred in the code.
Checking log files
Checking log files can help to identify errors that occur during runtime.
Java libraries and frameworks
Java offers various libraries and frameworks such as Spring, Hibernate, and Apache Struts that can help to prevent this error.
Spring
Spring provides a lightweight framework for developing web applications and offers features such as dependency injection and aspect-oriented programming.
Hibernate
Hibernate is a popular object-relational mapping (ORM) framework that simplifies database access in Java applications.
Apache Struts
Apache Struts is a framework for developing web applications that follows the model-view-controller (MVC) architecture .
Other helpful code examples for fixing the ‘class java.lang.Integer cannot be cast to class java.lang.Long’ error in Java
In java, java.lang.long cannot be cast to java.lang.integer code example
In java, java.lang.long cannot be cast to java.lang.integer code example
In java, class java.lang.Integer cannot be cast to class java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base of loader ‘bootstrap’) code example
// on my case, instead of casting I did:Long variable = Long.valueOf(variable.get("Attribute").toString());
Conclusion
In conclusion, the “class java.lang.Integer cannot be cast to class java.lang.Long” error can occur due to various reasons such as improper typecasting, usage of the wrong data type, and handling Number subclasses. To fix this error, one should use Integer.valueOf() or convert the Long object to a string using String.valueOf(). Best practices such as following naming conventions, using proper indentation, and writing clear and concise code can prevent this error from occurring. Debugging tools such as Eclipse and NetBeans can help to identify errors in Java code, and java libraries and frameworks such as Spring, Hibernate, and Apache Struts can prevent this error.
Frequently Asked Questions — FAQs
What is the cause of the «class java.lang.Integer cannot be cast to class java.lang.Long» error in Java?
The error occurs when there is an attempt to cast an Integer object to a Long object or vice versa in Java. It can also occur due to improper typecasting, handling Number subclasses, or reading a Parquet file.
How can I fix the «class java.lang.Integer cannot be cast to class java.lang.Long» error in Java?
To fix this error, one should either use Integer.valueOf() or convert the Long object to a string using String.valueOf(). Using generics while using Collections can also prevent ClassCastException. If the error occurs due to the usage of the wrong data type, changing the data type to the correct one can fix the error.
What are some best practices to prevent the «class java.lang.Integer cannot be cast to class java.lang.Long» error in Java?
Following naming conventions, using proper indentation, and writing clear and concise code can prevent this error from occurring. Using auto-boxing and auto-unboxing features in Java can also prevent this error.
What are some debugging tips for Java code related to the «class java.lang.Integer cannot be cast to class java.lang.Long» error?
Debugging tools such as Eclipse and NetBeans can help to identify errors in Java code. Printing out variable values can help to identify where the error occurred in the code. Checking log files can also help to identify errors that occur during runtime.
What Java libraries and frameworks can help to prevent the «class java.lang.Integer cannot be cast to class java.lang.Long» error?
Java offers various libraries and frameworks such as Spring, Hibernate, and Apache Struts that can help to prevent this error. Spring provides a lightweight framework for developing web applications and offers features such as dependency injection and aspect-oriented programming. Hibernate is a popular ORM framework that simplifies database access in Java applications. Apache Struts is a framework for developing web applications that follows the MVC architecture.
How can I prevent typecasting errors in Java with Integer and Long classes?
Using proper data types, avoiding unnecessary type conversions, and using the instanceof operator can prevent typecasting errors in Java with Integer and Long classes.