[英]Object instanceof Integer returns false
Object obj = "1234";
System.out.println(obj instanceof Integer);
What else should I do to check such Object if its an instanceof Integer or Float.如果它是整数或浮点数的实例,我还应该做些什么来检查此类对象。
Well it returns false because obj is not an Integer
, it's a reference to a String
object.好吧,它返回 false 因为 obj 不是
Integer
,它是对String
对象的引用。
Object obj = "1234";
try {
int value = ((Integer) obj);
} catch (ClassCastException e) {
// failed
}
or或者
Object obj = "1234";
try {
int value = Integer.parseInt((String)obj);
} catch (NumberFormatException e) {
// failed
}
Your obj
is a String
, the one below can return true
你的
obj
是一个String
,下面的可以返回true
Object obj = new Integer(1234);
Or或者
Object obj = 1234;
Try this尝试这个
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");
}
Any thing between ""
is String. ""
之间的任何东西都是字符串。 You are checking String against Integer that's why it's giving false .您正在检查 String 对 Integer 这就是它给出false的原因。
Try Object obj = 1234;
尝试
Object obj = 1234;
It will change the primitive type int
to Integer
by autoboxing .它将通过自动装箱将原始类型
int
更改为Integer
。
or或者
Object obj=new Integer(123);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.