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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:54:35  来源:igfitidea点击:

How to find out if a Object isa integer or isa string or isa boolean?

java

提问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:

JLS 15.20.2

RelationalExpressioninstanceofReferenceType

At run time, the result of the instanceofoperator is trueif the value of the RelationalExpressionis not nulland the reference could be cast (§15.16) to the ReferenceTypewithout raising a ClassCastException. Otherwise the result is false.

关系表达式instanceof参考类型

在运行时,instanceof运算符的结果是RelationalExpressiontrue的值是否不是,并且可以将引用强制转换(第 15.16 节)到ReferenceType而不会引发。否则结果是。nullClassCastExceptionfalse

Looking at your usage pattern, though, it looks like you may have bigger issues than this.

但是,查看您的使用模式,您似乎遇到了比这更大的问题。