java - 将Integer转换为Long
我需要使用反射来获取字段的值。 碰巧我并不总是确定该字段的数据类型是什么。 为此,为了避免一些代码重复,我创建了以下方法:
@SuppressWarnings("unchecked")
private static T getValueByReflection(VarInfo var, Class> classUnderTest, Object runtimeInstance) throws Throwable {
Field f = (processFieldName(var));
(true);
T value = (T) (runtimeInstance);
return value;
}
并使用此方法,如:
Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
要么
Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);
问题是我似乎无法将Integer投射到Long:
: cannot be cast to
有没有更好的方法来实现这一目标?
我使用的是Java 1.6。
13个解决方案
113 votes
只是:
Integer i = 7;
Long l = new Long(i);
vahid kh answered 2019-08-13T04:30:29Z
79 votes
不,您不能将Integer转换为Long,即使您可以从int转换为long.对于已知为数字且您想获得长值的单个值,您可以使用:
Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = ();
对于阵列,它会更棘手......
Jon Skeet answered 2019-08-13T04:30:10Z
42 votes
Integer i = 5; //example
Long l = (());
这样可以避免转换为String时的性能损失。 Integer中的longValue()方法只是int值的强制转换。 ()方法为vm提供了使用缓存值的机会。
Rich MacDonald answered 2019-08-13T04:30:56Z
18 votes
奇怪的是,我发现如果你从一个字符串解析它是有效的。
int i = 0;
Long l = ((i));
int back = ((l));
赢得。
Anon answered 2019-08-13T04:31:29Z
7 votes
通过添加' L'直接将整数转换为long。 到整数结束。
Long i = 1234L;
Jeff Johny answered 2019-08-13T04:31:55Z
6 votes
将整数转换为长非常简单且有很多方法可以转换它
例1
new Long(your_integer);
例2
(your_integer);
例3
Long a = 12345L;
例4
如果您已将int类型化为Integer,则可以执行以下操作:
Integer y = 12;
long x = ();
Naresh Kumar answered 2019-08-13T04:32:41Z
5 votes
如果Integer不为null
Integer i;
Long long = (i);
valueOf将自动强制转换为new。
使用valueOf而不是new允许编译器或JVM缓存此值(如果它很小),从而产生更快的代码。
lostintranslation answered 2019-08-13T04:33:22Z
4 votes
((Number) intOrLongOrSomewhat).longValue()
cingulata answered 2019-08-13T04:33:41Z
1 votes
如果您知道Integer不是NULL,则可以这样做:
Integer intVal = 1;
Long longVal = (long) (int) intVal
Steven Spungin answered 2019-08-13T04:34:08Z
1 votes
new Long(());
要么
new Long(());
Pavlo Zvarych answered 2019-08-13T04:34:29Z
1 votes
从int变量到long类型的解析器包含在Integer类中。 这是一个例子:
int n=10;
long n_long=(n);
您可以轻松使用此内置函数来创建从int解析为long的方法:
public static long toLong(int i){
long l;
if (i<0){
l=-((i));
}
else{
l=(i);
}
return l;
}
Bremsstrahlung answered 2019-08-13T04:35:04Z
0 votes
这是无效的
Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp == null ? null : ();
adkisson answered 2019-08-13T04:35:30Z
-1 votes
如果是Long类型的List,则将L添加到每个Integer值的末尾
List list = new ArrayList();
list = (1L, 2L, 3L, 4L);
Joydeep Dutta answered 2019-08-13T04:35:58Z