0

我有java.lang.Object一个函数的返回类型。我想验证Object返回的任何值是否为数字类型(doublelongintbyte或或DoubleLongByteFloatDouble......),如果它是真的想要转换为整数包装器引用类型。此外,如果Object实例包含一个String值,我希望它存储在字符串引用中。

4

4 回答 4

4

具有Object函数的返回类型。我想验证返回的任何 Object 值是否为数字类型(double 或 long 或 int 或 byte 或 Double 或 Long 或 Byte 或 Float 或 Double ....)

if (obj instanceof Number)
    ...


如果它是真的想要转换成一个整数包装器引用类型

if ...
    val = (Integer) ((Number) obj).intValue();


此外,如果 Object 实例包含一个 String 值,我希望它存储在 String 引用中。

...
else if (obj instanceof String)
    val = obj;
于 2012-08-21T07:30:29.780 回答
0

您可以执行以下操作:

Object obj = getProcessedObject();
if(obj instanceof Number) {
    // convert into a Integer wrapper reference type
Integer ref1 = ((Number)obj).intValue();
}
if(obj instanceof String) {
// process object for String
String ref = (String)obj;
}
于 2012-08-21T07:31:51.483 回答
0

返回 Object 的方法不能返回基本类型,如 double、long 或 int。

您可以使用 instanceof 检查实际返回的类型:

if (object instanceof Number){
    // want to convert into a Integer wrapper reference type
    object = ((Number)object).intValue();  // might lose precision
}

您可以通过类型转换分配给 String 变量

if (object instanceof String){
   stringVariable = (String)object;
}
于 2012-08-21T07:32:00.203 回答
0

尽管您可能有一个严重的设计问题,但为了实现您想要的,您可以使用 instanceof 运算符或 getClass() 方法:

Object o = myFunction();
if(o instanceof Integer) { //or if o.getClass() == Integer.class if you want 
                       only objects of that specific class, not the superclasses
   Integer integer = (Integer) o;
   int i = integer.intValue();
}
   //do your job with the integer
if(o instanceof String)
   //String job
于 2012-08-21T07:32:39.863 回答