Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Integer to Long

I need to get the value of a field using reflection. It so happens that I am not always sure what the datatype of the field is. For that, and to avoid some code duplication I have created the following method:

@SuppressWarnings("unchecked") private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable {   Field f = classUnderTest.getDeclaredField(processFieldName(var));   f.setAccessible(true);   T value = (T) f.get(runtimeInstance);    return value; } 

And use this method like:

Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance); 

or

Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance); 

The problem is that I can't seem to cast Integer to Long:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long 

Is there a better way to achieve this?

I am using Java 1.6.

like image 261
Tiago Veloso Avatar asked Jul 14 '11 08:07

Tiago Veloso


People also ask

Do you need to cast int to long?

Since int is smaller data type than long, it can be converted to long with a simple assignment. This is known as implicit type casting or type promotion, compiler automatically converts smaller data type to larger data type.

How do you make a long value?

To initialize long you need to append "L" to the end. It can be either uppercase or lowercase. All the numeric values are by default int . Even when you do any operation of byte with any integer, byte is first promoted to int and then any operations are performed.

Can int be added to long?

Yes, you can add a long and an int just fine, and you'll end up with a long . The int undergoes a widening primitive conversion, as described in the Java Language Specification, specifically JLS8, §5.1. 2 .

Can you convert a string to a long?

We can convert String to long in java using Long. parseLong() method.


1 Answers

Simply:

Integer i = 7; Long l = new Long(i); 
like image 109
vahid kh Avatar answered Nov 11 '22 02:11

vahid kh