gpt4 book ai didi

Java 不能从盒装类型转换为原始类型

转载 作者:行者123 更新时间:2023-12-03 21:48:02 25 4
gpt4 key购买 nike

我正在尝试使用 Class.cast () 将盒装 Double 转换为原始 double :

Object d = 1.0d;
Class<?> clazz = double.class;
//the bellow line throws java.lang.ClassCastException:
//Cannot cast java.lang.Double to double
clazz.cast(d);

我这样做是因为在我的代码的某些部分中,值对象和类是动态给出的,并且我确实保证值对象是兼容类型。但是这个异常(exception)真的让我很困惑。使用 cast () 的契约(Contract)是什么?

更新 我遇到了这个,因为我们有这样的代码:
interface Provider <T> {
T get ();
Class<T> getClazz();
}

//a special handling for double primitive
class DoubleProvider implements Provider<Double> {

public double getDouble(){
return 1.0d;
}

@Override
public Double get() {
return getDouble();
}

@Override
public Class<Double> getClazz() {
//why this actually compiles?
return double.class;
}
}

如果 double 和 Double 如此不同以至于它们都不能被认为是可以赋值的,为什么 java 允许 DoubleProvider 中的 getClazz() 方法进行编译? double.class 和 Double.class 之间有什么关系?

最佳答案

您不能转换 Doubledouble (反之亦然),因为两者都不是另一个的子类型。使用(double)而是自动取消装箱该值。

What is the contract of using cast()?



API 的 javadoc 是方法的约定。在这种情况下 javadoc says :

Casts an object to the class or interface represented by this Class object.

[...]

Throws: ClassCastException - if the object is not null and is not assignable to the type T.



如果您需要基于类获取对象的原始(未装箱)版本,我认为没有比这更好的方法了
if (clazz == double.class)
handleDouble((double) o);
if (clazz == int.class)
handleInt((int) o);
...

关于您的编辑:这是因为 double.class类型为 Class<Double> . JLS states :

The type of p.class, where p is the name of a primitive type (§4.2), is Class<B>, where B is the type of an expression of type p after boxing conversion (§5.1.7).

关于Java 不能从盒装类型转换为原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30218896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com