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();