是的,这是一段很简单的代码,但我仍然想知道是否有内置的替代品.
这是代码:
/** * 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库具有您寻求的方法: