如何使用 Java 中的 instanceOf 關鍵字來展示 Object 類?



問題描述

如何使用 instanceOf 關鍵字來展示 Object 類?

解決方案

此示例將 makeDisplayObjectClass() 方法設定成展示在這方法中作為引數傳遞的 Object 的類。

import java.util.ArrayList;
import java.util.Vector;

public class Main { 
   public static void main(String[] args) {
      Object testObject = new ArrayList();
      displayObjectClass(testObject);
   }
   public static void displayObjectClass(Object o) {
      if (o instanceof Vector) System.out.println(
         "Object was an instance of the class java.util.Vector");
      else if (o instanceof ArrayList) System.out.println(
         "Object was an instance of the class java.util.ArrayList");
      else System.out.println("Object was an instance of the " + o.getClass());
   }
}

結果

以上程式碼示例將產生以下結果。

Object was an instance of the class java.util.ArrayList
java_methods.htm
廣告
© . All rights reserved.