Java对象转换为Integer和String包装器

时间:2012-08-21 07:26:11

标签: java java-ee

我有一个函数的java.lang.Object返回类型。我想验证返回的Object值是否为数字类型(doublelongintbyteDouble或{{1 }}或LongByteFloat ....)如果它真的想要转换为整数包装器引用类型。此外,如果Double实例保存Object值,我希望它存储在String引用中。

4 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}

答案 3 :(得分: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