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.String
A에 대한 통화의 변수 인수
에 캐스팅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
'IT박스' 카테고리의 다른 글
JFrame의 닫기 버튼 클릭 이벤트를 캡처하는 방법은 무엇입니까? (0) | 2020.10.05 |
---|---|
Android Studio에서 기본 활동을 찾을 수 없습니다. (0) | 2020.10.05 |
Visual Studio 2005에서 Google C ++ 테스트 프레임 워크 (gtest)를 설정하는 방법 (0) | 2020.10.05 |
MySQL-하나의 INSERT 문에 몇 개의 행을 삽입 할 수 있습니까? (0) | 2020.10.05 |
긴 ASP.NET 작업에 대한 IIS 요청 시간 초과 (0) | 2020.10.05 |