为什么要null强制转换参数? [英] Why null cast a parameter?

查看:424
本文介绍了为什么要null强制转换参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When and why would somebody do the following:

doSomething( (MyClass) null );

您曾经做过这个吗?您能分享您的经验吗?

Have you ever done this? Could you please share your experience?

推荐答案

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

If doSomething is overloaded, you need to cast the null explicitly to MyClass so the right overload is chosen:

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

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

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

A non-contrived situation where you need to cast is when you call a varargs function:

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);
    }
}

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

The last line will produce the following warning:

Example.java:26:警告:非变量 不精确的varargs方法的调用 最后一个参数的参数类型;
转换为java.lang.String以获得可变参数 呼叫
广播到java.lang.String[] non-varargs调用并禁止显示 警告

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

这篇关于为什么要null强制转换参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆