我们的项目使用谷歌guava,Apache公用程序,也许其他库具有常见的任务,我想知道这些库是否包含空安全转换(对象到数字,对象到字符串)的方法。 至于现在我写了一些辅助方法,例如:
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; } }Our project use google guava, apache commons and maybe other libraries with common tasks and I was wondering if these libraries contain methods which does null safe conversions (object to number, object to string). As for now I wrote myself some helper methods, e.g :
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; } }最满意答案
我很确定在番石榴中没有这样的东西。 如前所述
番石榴试图强制你尽可能地避免使用null,因为在null存在的情况下,不正确的或无证的行为可能会导致大量的混淆和错误。 我认为尽可能避免使用空值绝对是一个好主意,如果您可以修改代码以使其不会使用空值,我强烈建议您采用这种方法。
类似的参数适用于parseEverythingAsInt 。 你正在寻找接受任何东西并返回一个int 。 这种方法的存在鼓励人们编写返回任何东西的方法。 这当然不是好的做法,因为严格有助于防止错误。 这就是为什么我很确定Guava没有这种方法。
也许我的回答最好是评论,但时间太长,我不认为会有积极的答案。
I'm pretty sure there's nothing like this in Guava. As already pointed
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.
A similar argument applies to parseEverythingAsInt. You're looking for a method accepting anything and returning an int. The very existence of such a method encourages people to write methods returning anything. This is surely no good practice, as being strict helps to prevent errors. That's why I'm quite sure there's no such method in Guava.
Maybe my answer should better be a comment, but it's too long and I don't think there'll be a positive answer, anyway.
更多推荐
发布评论