最佳答案
我需要使用反射获取字段的值。碰巧我并不总是确定字段的数据类型是什么。为此,为了避免一些代码重复,我创建了以下方法:
@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;
}
使用这种方法:
Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
或者
Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);
问题是,我似乎无法将 Integer
转换为 Long
:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
有没有更好的方法来实现这一点?
我正在使用 Java 1.6。