将null强制转换为任何类型

编程入门 行业动态 更新时间:2024-10-27 19:25:35
本文介绍了将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强制转换为任何类型

本文发布于:2023-06-10 05:42:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/608222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   类型   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!