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
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...
A parser from int variables to the long type is included in the Integer class. Here is an example:
int n=10;
long n_long=Integer.toUnsignedLong(n);
You can easily use this in-built function to create a method that parses from int to long:
public static long toLong(int i){
long l;
if (i<0){
l=-Integer.toUnsignedLong(Math.abs(i));
}
else{
l=Integer.toUnsignedLong(i);
}
return l;
}
Converting Integer to Long Very Simple and many ways to converting that
Example 1
new Long(your_integer);
Example 2
Long.valueOf(your_integer);
Example 3
Long a = 12345L;
Example 4
If you already have the int typed as an Integer you can do this:
Integer y = 12;
long x = y.longValue();
Simply:
Integer i = 7;
Long l = new Long(i);
If you know that the Integer is not NULL, you can simply do this:
Integer intVal = 1;
Long longVal = (long) (int) intVal
((Number) intOrLongOrSomewhat).longValue()