Java中對象的類型判斷
instanceof
判斷一個對象是否是一個類的實例,用Java中自帶的關鍵字instanceof似乎可以做到(僅從關鍵字名稱上可以猜測出),如下面的代碼:
public static void main(String args[]) {
Object i = new Integer(7);
if (i instanceof Number) {
System.out.println("Integer i is a Number");
} else {
System.out.println("Integer i isn't a Number");
}
if (i instanceof Serializable) {
System.out.println("Integer i is a Serializable");
} else {
System.out.println("Integer i isn't a Serializable");
}
if (i instanceof Integer) {
System.out.println("Integer i is an Integer");
} else {
System.out.println("Integer i isn't an Integer");
}
if (i instanceof Float) {
System.out.println("Integer i is a Float");
} else {
System.out.println("Integer i isn't a Float");
}
}
類定義部分為:
public abstract class Number implements java.io.Serializable {}
public final class Integer extends Number implements Comparable<Integer> {}
運行結果:
Console Output :
Integer i is a Number
Integer i is a Serializable
Integer i is an Integer
Integer i isn't a Float
然而好像和預期的不太一樣,能看出,使用該關鍵字不僅可以判斷對象是否是某個類的實例,甚至連該類繼承的基類和實現的接口也都能夠被識別為true,雖然這樣在邏輯上沒有任何問題,是可以把Integer當做一個Number來看來用,也當做一個Serializable來看來用,但是這樣返回的結果就沒有針對性了,太過於模糊,我們如果僅僅需要i instanceof Integer為true該怎麼做呢?
Class.equals
還好在Java有一個叫做Class的類,這是一個用來描述類信息的類,我們如果要精確判斷一個對象是否是具體的一個類的實例,可以這麼做:
public static void main(String args[]) {
Object i = new Integer(7);
if (i.getClass().equals(Number.class)) {
System.out.println("Integer i is a Number");
} else {
System.out.println("Integer i isn't a Number");
}
if (i.getClass().equals(Serializable.class)) {
System.out.println("Integer i is a Serializable");
} else {
System.out.println("Integer i isn't a Serializable");
}
if (i.getClass().equals(Integer.class)) {
System.out.println("Integer i is an Integer");
} else {
System.out.println("Integer i isn't an Integer");
}
if (i.getClass().equals(Float.class)) {
System.out.println("Integer i is a Float");
} else {
System.out.println("Integer i isn't a Float");
}
}