Mô tả
getClass() là phương thức final của lớp Object, trả về đối tượng Class<?> đại diện cho kiểu runtime của đối tượng. Mọi đối tượng Java đều kế thừa từ Object, nên đều có phương thức này.
Cú pháp
public final Class<?> getClass()
Ví dụ: Runtime type vs Compile-time type
class User {
private int id;
private String name;
public User(int id, String name) { this.id = id; this.name = name; }
}
class SpecificUser extends User {
private String specificId;
public SpecificUser(String specificId, int id, String name) {
super(id, name);
this.specificId = specificId;
}
}
public class GetClassDemo {
public static void main(String[] args) {
User user = new User(115, "Raja");
SpecificUser specificUser = new SpecificUser("AAA", 120, "Adithya");
User anotherSpecificUser = new SpecificUser("BBB", 125, "Jai"); // upcast
System.out.println(user.getClass()); // class User
System.out.println(specificUser.getClass()); // class SpecificUser
System.out.println(anotherSpecificUser.getClass()); // class SpecificUser (runtime type)
}
}
Kết quả
class User
class SpecificUser
class SpecificUser
Ứng dụng phổ biến
- Reflection: kiểm tra kiểu thực tế tại runtime.
- Logging/debug: in tên class động.
- Serialization frameworks (Jackson, Gson) dùng để xác định kiểu khi deserialize.
- Implement
equals()đúng chuẩn:if (getClass() != obj.getClass()) return false;
Lưu ý: getClass() không thể override. Để lấy class tĩnh, dùng MyClass.class.