示例 1: 使用 getClass() 检查对象的类
class Test1 { // first class } class Test2 { // second class } class Main { public static void main(String[] args) { // create objects Test1 obj1 = new Test1(); Test2 obj2 = new Test2(); // get the class of the object obj1 System.out.print("The class of obj1 is: "); System.out.println(obj1.getClass()); // get the class of the object obj2 System.out.print("The class of obj2 is: "); System.out.println(obj2.getClass()); } }
输出
The class of obj1 is: class Test1 The class of obj2 is: class Test2
在上面的例子中,我们使用了
Object
类的
getClass()
方法来获取
obj1对象的类名和
obj2。
要了解更多信息,请访问 Java Object getClass()。
示例 2: 使用 instanceOf 运算符检查对象的类
class Test { // class } class Main { public static void main(String[] args) { // create an object Test obj = new Test(); // check if obj is an object of Test if(obj instanceof Test) { System.out.println("obj is an object of the Test class"); } else { System.out.println("obj is not an object of the Test class"); } } }
输出
obj is an object of the Test class
在上面的例子中,我们使用了
instanceof
操作符来检查对象
obj 是否是类
Test 的实例。
示例 3: 使用 isInstance() 检查对象的类
class Test { // first class } class Main { public static void main(String[] args) { // create an object Test obj = new Test(); // check if obj is an object of Test1 if(Test.class.isInstance(obj)){ System.out.println("obj is an object of the Test class"); } else { System.out.println("obj is not an object of the Test class"); } } }
输出
obj is an object of the Test class
这里,我们使用了
Class
类的
isInstance()
方法来检查对象
obj是否是类的对象
测试。
isInstance()
方法的工作方式与
instanceof
操作符类似。但是,最好在运行时使用。