加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

是否有一个Java等同于C#的’checked’关键字?

发布时间:2020-12-15 02:53:48 所属栏目:Java 来源:网络整理
导读:是的,这是一段很简单的代码,但我仍然想知道是否有内置的替代品. 这是代码: /** * 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 Runtim
是的,这是一段很简单的代码,但我仍然想知道是否有内置的替代品.

这是代码:

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

解决方法

(预发布)开源Guava库具有您寻求的方法:

Ints.checkedCast(long)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读