我们的项目使用 google guava、apache commons 以及可能具有共同任务的其他库,我想知道这些库是否包含执行 null 安全转换(对象到数字、对象到字符串)的方法。至于现在我自己写了一些辅助方法,例如:
int parseInteger(Object obj) {
if (obj!= null) {
if (obj instanceof Integer) return (Integer) obj;
if (obj instanceof Long) return ((Long) obj).intValue();
return Integer.parseInt(obj.toString());
} else {
return 0;
}
}
最佳答案
我很确定在 Guava 中没有这样的东西。正如已经指出的
Guava tries to force you to avoid using null wherever possible, because improper or undocumented behavior in the presence of null can cause a huge amount of confusion and bugs. I think it's definitely a good idea to avoid using nulls wherever possible, and if you can modify your code so that it doesn't use null, I strongly recommend that approach instead.
类似的论点适用于 parseEverythingAsInt
。您正在寻找一种接受任何 并返回int
的方法。这种方法的存在鼓励人们编写返回任何东西的方法。这肯定不是好的做法,因为严格有助于防止错误。这就是为什么我很确定在 Guava 中没有这样的方法。
也许我的回答最好是评论,但它太长了,而且我认为无论如何不会有肯定的回答。
关于java - Java 中对象到数字到数字的转换。公共(public)库中有任何方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11184740/