【问题标题】:Object instanceof Integer returns false对象 instanceof 整数返回 false
【发布时间】:2014-04-03 09:58:00
【问题描述】:
Object obj = "1234";
System.out.println(obj instanceof Integer);

如果它是 Integer 或 Float 的实例,我还应该做什么来检查此类对象。

【问题讨论】:

  • 因为它是假的。这是一个字符串。
  • 阅读您的个人资料,这几乎感觉像是一个巨魔问题 - 您拥有 CS 硕士学位,您正在为 IBM 从事银行和安全应用程序工作,您的主要语言是 Java,但您没有不知道整数和字符串文字之间的区别?你来得太晚了,两天前是 4 月 1 日……但是说真的,你应该更新你的基础知识。官方教程的This section处理字符串和数字,this one处理转换。
  • 我应该解析它而不是检查 instanceof。

标签: java string integer instanceof


【解决方案1】:

它返回 false 因为 obj 不是 Integer,它是对 String 对象的引用。

Object obj = "1234";

try {
    int value = ((Integer) obj);
} catch (ClassCastException e) {
    // failed
}

Object obj = "1234";

try {
    int value = Integer.parseInt((String)obj);
} catch (NumberFormatException e) {
    // failed
}

【讨论】:

    【解决方案2】:

    你的objString,下面的可以回true

    Object obj = new Integer(1234);
    

    或者

    Object obj = 1234;
    

    【讨论】:

    • 我得到像“1234”这样的字符串作为参数。所以我不能使用 Object obj = 1234;
    • @ImranTariq 如果你知道你有一个字符串,为什么你认为它是一个整数?
    • @Joe 有很多可能的值。所以它可以是 String、Integer、Float 等。我并根据它检查类型和更改业务逻辑
    • @ImranTariq 好吧,它们真的被键入为 String、Integer 和 Float 吗?或者它们是用字符串编码的数字吗? “123.2”是一个字符串,就像“Joe”或“53”一样。如果它们被编码为字符串,则需要开始解析字符串并猜测它可能是哪种类型。
    【解决方案3】:

    试试这个

    try {
        int a = Integer.parseInt("1234");
        // No need to check instance of now, if supplied argument is number
        // then parseInt() will pass otherwise you will get exception.
    } catch (NumberFormatException e) {
        System.out.println("Supplied argument is not valid number");
    }
    

    【讨论】:

    • 看起来不错。而不是检查 instanceof 我应该解析它。
    【解决方案4】:

    "" 之间的任何东西都是字符串。您正在对照 Integer 检查 String 这就是它给出 false 的原因。

    试试Object obj = 1234;

    它将通过自动装箱将原始类型int 更改为Integer

    Object obj=new Integer(123);
    

    【讨论】:

    • @ImranTariq 试试这个。
    猜你喜欢
    • 2021-09-25
    • 2013-06-22
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    相关资源
    最近更新 更多