Converting Integer to Long

Tiago Veloso picture Tiago Veloso · Jul 14, 2011 · Viewed 374.2k times · Source

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.

Answer

vahid kh picture vahid kh · Sep 11, 2013

Simply:

Integer i = 7;
Long l = new Long(i);