运行时识别对象和类的信息主要有两种方式:一种是“传统的”RTTI,它默认我们在编译时已经知道了所有的类型;一种是反射,它允许我们在运行时发现和使用类的信息。
今天首先来认识下RTTI。
1.什么是RTTI以及为什么需要RTTI
RTTI的英文全称是Run-Time Type Identification,即运行时类型识别。它可以在程序运行时检查父类型的引用是否可以指向子类型的对象,即确保类型向上转换安全。
示例1:
abstract class Shape {
void draw() {
System.out.println(this + ".draw()");
}
abstract public String toString();
}
class Circle extends Shape {
public String toString() {
return "Circle";}
}
class Square extends Shape {
public String toString() {
return "Square"; }
}
class Triangle extends Shape {
public String toString() {
return "Triangle"; }
}
public class Shapes {
public static void main(String[] args) {
List<Shape> shapeList = Arrays.asList(new Circle(), new Square(), new Triangle