Is there a ‘checked’ keyword equivalent to c# in Java?

Yes, this is a very simple piece of code, but I still want to know if there is a built-in alternative

This is 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# is:

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

Solution

(pre release) the open source guava library has the methods you seek:

Ints. checkedCast(long)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>