简体   繁体   English

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

[英]Java Object Conversion to Integer and String wrapper

I have a java.lang.Object return type from a function. 我有一个函数的java.lang.Object返回类型。 I want to verify whatever Object value returned is of numeric type ( double or long or int or byte or Double or Long or Byte or Float or Double ....) and if it's true want to convert into a Integer wrapper reference type. 我想验证返回的任何Object值是数字类型( doublelongintbyteDoubleLongByteFloatDouble ....),如果是真的想要转换为Integer包装器引用类型。 Also if the Object instance holds a String value I want it to be stored in a String reference. 另外,如果Object实例包含一个String值,我希望将其存储在String引用中。

Have a Object return type from a function. 具有函数的Object返回类型。 I want to verify whatever Object value returned is of numeric type(double or long or int or byte or Double or Long or Byte or Float or Double ....) 我想验证返回的任何对象值都是数字类型(双精度或长整数或整数或字节或双精度或长整数或字节或浮点数或双精度..)

if (obj instanceof Number)
    ...


if it's true want to convert into a Integer wrapper reference type 如果是真的要转换为Integer包装器引用类型

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


Also If the Object instance holds a String value i want it to be stored in a String reference. 另外,如果Object实例包含一个String值,我希望将其存储在String引用中。

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

You can do something like : 您可以执行以下操作:

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

A method that returns Object cannot return primitive types like double, long, or int. 返回Object的方法不能返回基本类型,例如double,long或int。

You can check for the actual returned type using instanceof: 您可以使用instanceof检查实际返回的类型:

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

You can assign to a String variable by type-casting 您可以通过类型转换将其分配给String变量

if (object instanceof String){
   stringVariable = (String)object;
}

Although you probably have a serious design problem, in order to achieve what you want you can use instanceof operator or getClass() method: 尽管您可能遇到了严重的设计问题,但是要实现所需的功能,可以使用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