Java 示例 - 使用方法打印数组

  • 问题描述

    如何使用 instanceOf 关键字显示对象类?
  • 解决方案

    此示例使 displayObjectClass() 方法显示在此方法中作为参数传递的对象的类。
    
    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