gpt4 book ai didi

java - 为什么 null 强制转换参数?

转载 作者:IT老高 更新时间:2023-10-28 11:41:24 25 4
gpt4 key购买 nike

何时以及为什么有人会这样做:

doSomething( (MyClass) null );

你做过吗?可以分享一下你的经验吗?

最佳答案

如果 doSomething 被重载,您需要将 null 显式转换为 MyClass 以便选择正确的重载:

public void doSomething(MyClass c) {
// ...
}

public void doSomething(MyOtherClass c) {
// ...
}

当您调用可变参数函数时,需要强制转换的情况是:

class Example {
static void test(String code, String... s) {
System.out.println("code: " + code);
if(s == null) {
System.out.println("array is null");
return;
}
for(String str: s) {
if(str != null) {
System.out.println(str);
} else {
System.out.println("element is null");
}
}
System.out.println("---");
}

public static void main(String... args) {
/* the array will contain two elements */
test("numbers", "one", "two");
/* the array will contain zero elements */
test("nothing");
/* the array will be null in test */
test("null-array", (String[])null);
/* first argument of the array is null */
test("one-null-element", (String)null);
/* will produce a warning. passes a null array */
test("warning", null);
}
}

最后一行将产生以下警告:

Example.java:26: warning: non-varargs call of varargs method with inexact argument type for last parameter;
cast to java.lang.String for a varargs call
cast to java.lang.String[] for a non-varargs call and to suppress this warning

关于java - 为什么 null 强制转换参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/315846/

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