Java 如何确定对象是整数还是 isa 字符串或 isa 布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2391955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find out if a Object isa integer or isa string or isa boolean?
提问by Pentium10
I have an object and I want to detect what type is, so I can call
我有一个对象,我想检测什么类型,所以我可以调用
if (obj isa Integer)
put(key,integerval);
if (obj isa String)
put(key,stringval);
if (obj isa Boolean)
put(key,booleanval);
采纳答案by polygenelubricants
You're pretty close, actually!
实际上,您非常接近!
if (obj instanceof Integer)
put(key,integerval);
if (obj instanceof String)
put(key,stringval);
if (obj instanceof Boolean)
put(key,booleanval);
From the JLS 15.20.2:
RelationalExpression
instanceof
ReferenceTypeAt run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpressionis notnull
and the reference could be cast (§15.16) to the ReferenceTypewithout raising aClassCastException
. Otherwise the result isfalse
.
关系表达式
instanceof
参考类型在运行时,
instanceof
运算符的结果是RelationalExpressiontrue
的值是否不是,并且可以将引用强制转换(第 15.16 节)到ReferenceType而不会引发。否则结果是。null
ClassCastException
false
Looking at your usage pattern, though, it looks like you may have bigger issues than this.
但是,查看您的使用模式,您似乎遇到了比这更大的问题。