将整数转换为长整数 [英] Converting Integer to Long
问题描述
我需要使用反射获得字段的值。这样发生,我不总是确定字段的数据类型。为此,为了避免一些代码重复,我创建了以下方法:
@SuppressWarnings(unchecked)
private static< T> throws Throwable {
Field f = classUnderTest.getDeclaredField(processFieldName(var)); T getValueByReflection(VarInfo var,Class<?> classUnderTest,Object runtimeInstance)
f.setAccessible(true);
T value =(T)f.get(runtimeInstance);
返回值;
}
并使用此方法:
Long value1 = getValueByReflection(inv.var1(),classUnderTest,runtimeInstance);
或
Double [] value2 = getValueByReflection(inv.var2(),classUnderTest,runtimeInstance);
问题是我似乎不能转换 Integer
到长
:
java.lang.ClassCastException: java.lang.Integer不能转换为java.lang.Long
有更好的方法来实现
不,您不能将 Integer
转换为 Long
,即使您可以从 int
到
long
。对于已知为数字的个体值,您希望获取长值,可以使用:
Number tmp = getValueByReflection(inv.var1(),classUnderTest,runtimeInstance);
Long value1 = tmp.longValue();
对于数组,它会更棘手...
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.
No, you can't cast Integer
to Long
, even though you can convert from int
to long
. For an individual value which is known to be a number and you want to get the long value, you could use:
Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp.longValue();
For arrays, it will be trickier...
这篇关于将整数转换为长整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!