在Java中,如何使用instanceOf
關鍵字顯示Object
類?
下面範例中,顯示在displayObjectClass()
方法中作為引數傳遞的物件的類。
package com.yiibai;
import java.util.ArrayList;
import java.util.Vector;
public class displayObjectClass {
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