是否有一个java等价于c的“checked”关键字?

yshpjwxd  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(261)

是的,这是一段微不足道的代码,但我仍然想知道是否有一个内置的替代品。
代码如下:

/**
 * 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;
}
a6b3iqyw

a6b3iqyw1#

不,java没有像c#那样的自动信息溢出或丢失检查。

dohp0rv5

dohp0rv52#

(预发行版)开源guava库有您寻求的方法:
内部检查广播(长)

kxeu7u2r

kxeu7u2r3#

不,没有等价物,看看这个关键字表。

相关问题