开发者

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

开发者 https://www.devze.com 2022-12-10 15:31 出处:网络
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:

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开发者_Go百科 (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;
}


No there's no equivalent, check out this keyword chart.


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

Ints.checkedCast(long)


No. Java doesn't have any automatic overflow or loss of information checking like C# does.

0

精彩评论

暂无评论...
验证码 换一张
取 消