什么时候可以在Java中使用getClass()方法?
getClass()方法是从对象 类,它返回一个类类的实例。当我们声明一个对象的新实例时,它将引用一个类。每个JVM只能有一个类,但有多个对象引用该类。因此,当我们获得两个对象的类时,它们可能是指同一类。
语法
public final Class<?> getClass()
示例
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 TestUser { 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"); System.out.println(user.getClass()); System.out.println(specificUser.getClass()); System.out.println(anotherSpecificUser.getClass()); } }
输出结果
class User class SpecificUser class SpecificUser