JavagetClass()方法
示例
该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()方法将返回最特定的类类型,这就是为什么在getClass()调用时anotherSpecificUser,返回值的classSpecificUser原因是它比继承树低User。
值得注意的是,尽管该getClass方法声明为:
public final native Class<?> getClass();
调用返回的实际静态类型getClass是Class<?extendsT>whereT是getClass被调用对象的静态类型。
即以下将编译:
Class<? extends String> cls = "".getClass();