我有一个函数的java.lang.Object
返回类型。我想验证返回的Object
值是否为数字类型(double
或long
或int
或byte
或Double
或{{1 }}或Long
或Byte
或Float
....)如果它真的想要转换为整数包装器引用类型。此外,如果Double
实例保存Object
值,我希望它存储在String引用中。
答案 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