IT박스

null이 매개 변수를 캐스팅하는 이유는 무엇입니까?

itboxs 2020. 10. 5. 07:45
반응형

null이 매개 변수를 캐스팅하는 이유는 무엇입니까? [복제]


이 질문에 이미 답변이 있습니다.

누군가가 다음을 수행하는시기와 이유 :

doSomething( (MyClass) null );

이 일을 한 적이 있습니까? 경험을 공유해 주시겠습니까?


doSomething이 오버로드 된 경우 MyClass올바른 오버로드가 선택되도록 null을 명시 적으로 캐스팅해야합니다 .

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 메소드의 비 varargs 호출;
에 캐스팅 java.lang.StringA에 대한 통화의 변수 인수
에 캐스팅 java.lang.String[]A가 전화를 비 가변 인자와이 경고를 억제하기 위해


Let's say you have these two functions, and assume that they accept null as a valid value for the second parameters.

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

These two methods differ only by the type of their second parameters. If you want to use one of them with a null as the second parameter, you must cast the null to the type of second argument of the corresponding function, so that compiler can decide which function to call.

To call the first function: ShowMessage("Test", (Control) null);
For the second: ShowMessage("Test2", (MyDelegate) null);

참고URL : https://stackoverflow.com/questions/315846/why-null-cast-a-parameter

반응형