Java如何用instanceof关键字来显示Object类?
如何用instanceof关键字来显示Object类?
解决方法
这个例子让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