繁体   English   中英

Java对象转换为整数和字符串包装器

[英]Java Object Conversion to Integer and String wrapper

我有一个函数的java.lang.Object返回类型。 我想验证返回的任何Object值是数字类型( doublelongintbyteDoubleLongByteFloatDouble ....),如果是真的想要转换为Integer包装器引用类型。 另外,如果Object实例包含一个String值,我希望将其存储在String引用中。

具有函数的Object返回类型。 我想验证返回的任何对象值都是数字类型(双精度或长整数或整数或字节或双精度或长整数或字节或浮点数或双精度..)

if (obj instanceof Number)
    ...


如果是真的要转换为Integer包装器引用类型

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


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

...
else if (obj instanceof String)
    val = obj;

您可以执行以下操作:

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;
}

返回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;
}

尽管您可能遇到了严重的设计问题,但是要实现所需的功能,可以使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM