我需要使用反射来获取字段的值。碰巧我并不总是确定该字段的数据类型是什么。为此,为了避免一些代码重复,我创建了以下方法:
@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。
最佳答案
简单地说:
Integer i = 7;
Long l = new Long(i);
关于java - 将整数转换为长整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6690745/