将null强制转换为任何类型

将null强制转换为任何类型

本文介绍了将null强制转换为任何类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以强制转换为任何类型吗?即以下代码可以正常工作

Can null be casted to any type? i.e. will the following code work

public <T> T foo(Object object){
    return (T) object;
}

Duck duck = foo(new Duck()); // this works

Duck duck2 = foo(null); // should this work?
Cat cat = foo(null); // should this work?

// if they are both null, should this be true?
boolean equality = duck2.equals(cat);

我的问题是 null 'castable

My question is, is null 'castable to anything'?

推荐答案

来自Javadocs:

From Javadocs:

还有一种特殊的null类型,即表达式null的类型,其中没有名称。由于空类型没有名称,因此无法声明空类型的变量或将其强制转换为空类型。空引用是空类型表达式的唯一可能的值。空引用始终可以转换为任何引用类型。实际上,程序员可以忽略null类型,而假装null只是可以是任何引用类型的特殊文字。

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

这篇关于将null强制转换为任何类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 01:59