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.
Number[]
and a loop over it to create an appropriately typed array, right? – Fuliginous