在 Java 中使用 null 调用方法


當對 null 參照呼叫方法時,它會擲出 NullPointerException,但如果遇到靜態方法,我們可以使用轉型表達式讓呼叫成為可能。請看以下範例 −

範例

線上範例

public class Tester {
   public static void display(){
      System.out.println("display");
   }
   private void print() {
      System.out.println("print");
   }

   public static void main(String[] args) {
      //Scenario 1:
      //Calling a method on null reference
      //causes NullPointerException
      try {
         Tester test = null;           test.print();
      }catch(Exception e) {
         System.out.println(e.getMessage());
      }

      //Scenario 2:
      //Static method can be invoked
      //on a null object by using the casting expression
      ((Tester)null).display();
   }
}

輸出

null
display

備註

  • 情境 1 示範導致 NullPointerException 的程式碼。

  • 情境 2 示範透過評估 null 物件的類別名稱來使用靜態方法。

更新日期: 2020-06-18

584 次瀏覽

启动你的职业生涯

通过完成课程来获得认证

开始
广告
© . All rights reserved.