当前位置: 代码迷 >> java >> 为什么使用null强制转换作为参数?
  详细解决方案

为什么使用null强制转换作为参数?

热度:109   发布时间:2023-08-02 10:45:57.0

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

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:warning:非varargs调用varargs方法,最后一个参数的参数类型不精确;
转换为java.lang.String以进行varargs调用
转换为java.lang.String[]以进行非varargs调用并禁止此警告

假设您有这两个函数,并假设它们接受null作为第二个参数的有效值。

void ShowMessage(String msg, Control parent);
void ShowMessage(String msg, MyDelegate callBack);

这两种方法的区别仅在于它们的第二个参数的类型。 如果要使用其中一个以null作为第二个参数,则必须将null转换为相应函数的第二个参数的类型,以便编译器可以决定调用哪个函数。

要调用第一个函数: ShowMessage("Test", (Control) null);
对于第二个: ShowMessage("Test2", (MyDelegate) null);

  相关解决方案