Java 程序:确定对象的类

要理解此示例,您应了解以下Java编程主题


示例 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() 方法来获取对象 obj1obj2 的类名。

要了解更多,请访问 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 是否是 Test 类的对象。

isInstance() 方法与 instanceof 运算符的工作方式类似。但是,它在运行时更受欢迎。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战