在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