Tiago Veloso Tiago Veloso - 5 months ago 18
Java Question

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:

private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable {
Field f = classUnderTest.getDeclaredField(processFieldName(var));
T value = (T) f.get(runtimeInstance);

return value;

And use this method like:

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


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

The problem is that I can't seem to cast

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.


No, you can't cast Integer to Long, even though you can convert from int to long. For an individual value which is known to be a number and you want to get the long value, you could use:

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

For arrays, it will be trickier...