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