将整数转换为长整数 [英] Converting Integer to Long

查看:167
本文介绍了将整数转换为长整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用反射获得字段的值。这样发生,我不总是确定字段的数据类型。为此,为了避免一些代码重复,我创建了以下方法:

  @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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆