Java 运行时类型识别
运行时类型识别(Runtime Type Identification),简称RTTI,是一种在运行时获取对象类型的功能。对于多态性来说,它非常关键,因为我们需要确定哪个方法将被执行。我们也可以对原始数据类型如整数、浮点数和其他数据类型实现它。
本文将通过示例解释Java中运行时类型识别的用例。
运行时类型识别的程序
让我们讨论一些可以帮助我们识别对象类型的方法:
instanceOf
这是一个比较运算符,用于检查一个对象是否是指定类的实例。它的返回类型是布尔值,如果对象是给定类的实例,则返回true,否则返回false。
语法
nameOfObject instanceOf nameOfClass;
getClass()
它是‘java.lang’包的一个方法,用于返回指定对象的运行时类。它不接受任何参数。
语法
nameOfObject.getClass();
这是调用该方法的通用语法。
getName()
它返回指定类的对象的类、接口和原始类型的名称。其返回类型是String。
语法
nameOfClassobject.getName();
示例1
以下示例演示了instanceOf的使用。
public class Main {
public static void main(String[] args) {
String st1 = "Tutorials Point";
if(st1 instanceof String) {
System.out.println("Yes! st1 belongs to String");
} else {
System.out.println("No! st1 not belongs to String");
}
}
}
输出
Yes! st1 belongs to String
在上面的代码中,我们声明并初始化了一个字符串。if-else块使用instanceOf检查了‘st1’是否是字符串类型。
示例2
在下面的示例中,我们使用getClass()和getName()方法来比较两个对象是否属于相同类型。
import java.util.*;
class Student {
String name;
int regd;
Student(String name, int regd) {
// Constructor
this.name = name;
this.regd = regd;
}
}
public class Main {
public static void main(String[] args) {
// creating objects of Class student
Student st1 = new Student("Tutorialspoint", 235);
Student st2 = new Student("Tutorix", 2011);
// retrieving class name
Class cls1 = st1.getClass();
Class cls2 = st2.getClass();
// checking whether name of objects are same or not
if(cls1.getName() == cls2.getName()) {
System.out.println("Both objects belongs to same class");
} else {
System.out.println("Both objects not belongs to same class");
}
}
}
输出
Both objects belongs to same class
示例3
在这个特定的示例中,我们将声明和初始化两个基本类型和它们对应的包装类。然后,使用getClass()方法获取它们的类名。
public class Main {
public static void main(String[] args) {
double d1 = 50.66;
int i1 = 108;
// Wrapper class of double and integer
Double data1 = Double.valueOf(d1);
Integer data2 = Integer.valueOf(i1);
System.out.println("Value of data1 = " + data1 + ", its type: " + data1.getClass());
System.out.println("Value of data2 = " + data2 + ", its type: " + data2.getClass());
}
}
输出
Value of data1 = 50.66, its type: class java.lang.Double
Value of data2 = 108, its type: class java.lang.Integer
结论
在本文中,我们探讨了运行时类型识别,它更多地是一种类型内省。当我们需要比较两个对象或在多态性中需要时,我们使用这个特性,因为它允许我们检索有关类、接口等的信息片段。