java - Java 中对象到数字到数字的转换。公共(public)库中有任何方法吗?

标签 java guava apache-commons

我们的项目使用 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/

相关文章:

java - 并发写入 titan DB 以提高性能

java - 使用 Guava 的基础知识

java - 如何按插入顺序迭代 Multimap?

java - 是否可以在运行时提供新的 PropertiesConfiguration 文件?

java - prunsrv.exe 是否使用多个线程将 Java 应用程序作为服务运行?

java - Maven 似乎使用的版本比我预期的版本旧

java - 动态编辑属性文件

java - 如何在枚举单例中实现日志记录?

java - Guava 如何将所有文件从一个目录复制到另一个目录

java ftp 空指针异常