No, there is no way to do this. obj
is of type Object
(even though it is a Double
instance), and the Object
class does not have such methods as doubleValue()
. The proper way would indeed be to cast:
Double d = (Double) obj;
Domanda
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.
Soluzione
No, there is no way to do this. obj
is of type Object
(even though it is a Double
instance), and the Object
class does not have such methods as doubleValue()
. The proper way would indeed be to cast:
Double d = (Double) obj;
Altri suggerimenti
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.
You cannot.
Since your reference is to an Object
, you will only have the methods which Object
has at its disposal.
Note that you can use Number
, which is the superclass of Integer
, Short
, etc and which defines .doubleValue()
:
final Number n = new Double(2.0);
n.doubleValue(); // works
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.
No, it's not possible. The instance obj
is a reference to an Object
and can see only the methods of the Object
class. You must cast it to Double
to use specific methods of the Double
class.
No! The only alternative is to use:
obj.toString()
Or, to use as double:
Double.parseDouble(obj.toString())
But it is not a good practice. Certainly has some another good alternative to your case. Post your code