我需要使用反射获得字段的值。这样发生,我不总是确定字段的数据类型。为了避免一些代码重复,我创建了以下方法:
@SuppressWarnings("unchecked")
private static 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;
}
并使用此方法如:
Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
要么
Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);
问题是,我似乎不能把整数转换为长:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
有没有更好的方法来实现这一点?
我使用Java 1.6。