Java教程

Java 确定对象类的程序

Java 程序确定对象的类

在这个例子中,我们将学习在 Java 中使用 getClass() 方法、instanceof 运算符和 isInstance() 方法确定对象的类。
要理解此示例,您应该了解以下Java 编程主题:
Java 类和对象 Java instanceof Operator

示例 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 操作符类似。但是,最好在运行时使用。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4