是否有一个Java等同于C#的’checked’关键字?
发布时间:2020-05-29 00:43:00 所属栏目:Java 来源:互联网
导读:是的,这是一段很简单的代码,但我仍然想知道是否有内置的替代品. 这是代码: /** * Cast x to int, throw an exception if theres loss of information */public static int safeLongToInt(long x){ int result = (int) x; if (result != x)
|
是的,这是一段很简单的代码,但我仍然想知道是否有内置的替代品. 这是代码: /**
* 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) (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
