简体   繁体   中英

Is there a Java equivalent to C#'s 'checked' keyword?

Yes, it's a trivial piece of code to write, but I still wonder if there's a built-in replacement.

Here's the code:

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

The code in C# would be:

int foo;
long bar = ...;
checked
{
  foo = bar;
}

不,没有相应的,请查看此关键字图表

The (pre-release) open-source Guava library has the method you seek:

Ints.checkedCast(long)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM