我需要使用反射来获取字段的值。碰巧我并不总是确定该字段的数据类型是什么。为此,为了避免一些代码重复,我创建了以下方法:
@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。
原文由 Tiago Veloso 发布,翻译遵循 CC BY-SA 4.0 许可协议
不,即使您可以从
int
Long
您也不Integer
--- 转换为long
。对于已知为数字的 单个 值并且您想要获得长值,您可以使用:对于数组,它会更棘手……