Java 程序来确定对象的类
要理解此示例,您应该具备以下 Java 编程的知识:
示例 1:使用 getClass() 检查对象的类
public class Test1 {
// first class
}
public class Test2 {
// second class
}
public 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 运算符检查对象的类
public class Test {
// class
}
public 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() 检查对象的类
public class Test {
// first class
}
public 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
运算符类似。但是,它是运行时的首选。