2008-11-24 114 views
80

我看到这段代码的地方,并想知道:什么时候和为什么会有人做到以下几点:为什么null投射?

doSomething((MyClass) null); 

你有没有这样做呢?你能分享你的经验吗?

+0

也许只是一个没有经验的编码器?或者是从doSomething改变代码的人((cast)something);并希望将其更改为无效,只是不打算删除演员?它是在多个地方还是只有一个实例? – 2008-11-24 23:20:26

+0

我不记得自己在哪里读过它,但是我看到了这一点,并了解到可以将null指定给对象。问题是,我找不到合理的场景! :P – pek 2008-11-24 23:22:11

回答

125

如果doSomething超载,你需要显式转换为null MyClass所以正确的超载选择:

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

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

非做作的情况下,你需要转换的,当你调用一个可变参数功能:

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:non-varargs 调用可变参数方法不准确 参数类型为最后一个参数;
投给java.lang.String的可变参数 呼叫
投给java.lang.String[]的 非可变参数调用,并抑制这种 警告

32

比方说,你有这两个函数,并假定他们接受null为有效第二个参数的值。

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

这两种方法可以通过第二参数的类型而不同。如果你想用null中的一个作为第二个参数,你必须将null转换为相应函数的第二个参数的类型,以便编译器可以决定调用哪个函数。

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