Mastergeek
Mastergeek

Reputation: 429

java use object as double without explicit cast

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.

Upvotes: 1

Views: 192

Answers (6)

Andreas Fester
Andreas Fester

Reputation: 36650

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.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533640

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.

Upvotes: 2

elias
elias

Reputation: 15490

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

Upvotes: 0

fge
fge

Reputation: 121760

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

Upvotes: 2

eternay
eternay

Reputation: 3814

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.

Upvotes: 1

arshajii
arshajii

Reputation: 129537

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;

Upvotes: 5

Related Questions