Say I have this:
Object obj = new Double(3.14);
Is there a way to use obj like a Double without explicitly casting it to Double? For instance, if I wanted to use the .doubleValue() method of Double for calculations.
Say I have this:
Object obj = new Double(3.14);
Is there a way to use obj like a Double without explicitly casting it to Double? For instance, if I wanted to use the .doubleValue() method of Double for calculations.
The only way to do it if you can not cast is to use reflection:
Object obj = new Double(3.14);
Method m1 = obj.getClass().getMethod("doubleValue");
System.out.println("Double value: " + m1.invoke(obj));
Method m2 = obj.getClass().getMethod("intValue");
System.out.println("Int value: " + m2.invoke(obj));
Double value: 3.14
Int value: 3
This is usually only useful in some limited corner cases - normally, casting, generics, or using some supertype is the right approach.
The closest you can do is this
Number num = new Double(3.14);
double d= num.doubleValue();
You can only call methods that the compiler knows is available, not based on the runtime type of the objects.
In short Object doesn't have a doubleValue() method so you cannot call it. You have to have a reference type which has the method you want to call.