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.
-
3Do you have a question ?Nir Alfasi– Nir Alfasi2012-08-21 07:27:28 +00:00Commented Aug 21, 2012 at 7:27
4 Answers
Have a
Objectreturn 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;
3 Comments
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;
}
1 Comment
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
1 Comment
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;
}