简体   繁体   English

Java将对象用作双重对象而无需显式强制转换

[英]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 ? 有没有一种方法可以像Double一样使用obj而不将其显式转换为Double For instance, if I wanted to use the .doubleValue() method of Double for calculations. 例如,如果我想使用Double.doubleValue()方法进行计算。

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() . objObject类型的(即使它是Double 实例 ),并且Object类没有诸如doubleValue()这样的方法。 The proper way would indeed be to cast: 正确的方法确实是强制转换:

Double d = (Double) obj;

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. 既然你提到的是一个Object ,你只会有哪些方法Object在其处置。

Note that you can use Number , which is the superclass of Integer , Short , etc and which defines .doubleValue() : 请注意,您可以使用Number ,它是IntegerShort等的超类,并且定义了.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. 简而言之, Object没有doubleValue()方法,因此无法调用它。 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. 实例obj是对Object的引用,并且只能看到Object类的方法。 You must cast it to Double to use specific methods of the Double class. 您必须将其Double转换为Double才能使用Double类的特定方法。

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 发布您的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM