为什么要null转换参数?

什么时候以及为什么有人要执行以下操作:

doSomething( (MyClass) null );

你做过吗?您能否分享您的经验?

回答:

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

public void doSomething(MyClass c) {

// ...

}

public void doSomething(MyOtherClass c) {

// ...

}

调用varargs函数时,需要进行强制转换的情况是:

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:警告:varargs方法的无变量调用,最后一个参数的参数类型不精确;

强制转换java.lang.String为varargs调用

强制转换java.lang.String[]为非varargs调用并禁止显示此警告

以上是 为什么要null转换参数? 的全部内容, 来源链接: utcz.com/qa/398531.html

回到顶部