getClass() 方法

getClass() 方法可用於查詢物件的執行時類型別。請參閱以下示例:

public class User {
   
    private long userID;
    private String name;

    public User(long userID, String name) {
        this.userID = userID;
        this.name = name;
    }
}

public class SpecificUser extends User {
    private String specificUserID;

    public SpecificUser(String specificUserID, long userID, String name) {
        super(userID, name);
        this.specificUserID = specificUserID;
    }
}

public static void main(String[] args){
    User user = new User(879745, "John");
    SpecificUser specificUser = new SpecificUser("1AAAA", 877777, "Jim");
    User anotherSpecificUser = new SpecificUser("1BBBB", 812345, "Jenny");

    System.out.println(user.getClass()); //Prints "class User"
    System.out.println(specificUser.getClass()); //Prints "class SpecificUser"
    System.out.println(anotherSpecificUser.getClass()); //Prints "class SpecificUser"
}

getClass() 方法將返回最具體的類型別,這就是為什麼在 anotherSpecificUser 上呼叫 getClass() 時,返回值為 class SpecificUser,因為它比繼承樹低於 User

值得注意的是,雖然 getClass 方法被宣告為:

public final native Class<?> getClass();

呼叫 getClass 返回的實際靜態型別是 Class<? extends T>,其中 T 是呼叫 getClass 的物件的靜態型別。

即以下將編譯:

Class<? extends String> cls = "".getClass();