是的,这是一段微不足道的代码,但我仍然想知道是否有一个内置的替代品。
代码如下:
/**
* Cast x to int, throw an exception if there's loss of information
*/
public static int safeLongToInt(long x)
{
int result = (int) x;
if (result != x)
throw new RuntimeException("long doesn't fit in an int: " + x);
return result;
}
c中的代码是:
int foo;
long bar = ...;
checked
{
foo = bar;
}
3条答案
按热度按时间a6b3iqyw1#
不,java没有像c#那样的自动信息溢出或丢失检查。
dohp0rv52#
(预发行版)开源guava库有您寻求的方法:
内部检查广播(长)
kxeu7u2r3#
不,没有等价物,看看这个关键字表。