简体   繁体   中英

Java Object Conversion to Integer and String wrapper

I have a java.lang.Object return type from a function. 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. Also if the Object instance holds a String value I want it to be stored in a String reference.

Have a Object return type from a function. 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

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.

...
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.

You can check for the actual returned type using 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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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