RTTI——运行时类型识别(Run Time Type Identification,RTTI)
1.定义
定义1:当只有一个指向对象基类的引用时,RTTI机制可以让你找到这个对象的确切概念。
定义2:只有基础类型的一个句柄时,利用它判断一个对象的正确类型。
定义3:By Run Time Type Identification(RTTI) we denote a mechanism to find the type of an object at run time.
2.Java在运行期间查找对象和类信息的两种方式:
(1)传统RTTI:假定在编译和运行期间拥有所有类型;
特点:编译器会在编译期间打开和检查所有.class文件,我们可以用“普通”的方式调用一个对象的所有方法。
(2)反射机制:利用反射在运行期间独立查找类信息。
特点:.class文件在编译期间是不可使用的,而是由运行期环境打开和检查。
3.RTTI Mechanism:
Typically, there are two situations when the RTTI mechanism is used:
·downcasting to a child class
·checking an object type via instanceof
4.Downcasting
Assume we have the following hierarchy:
//upcasting - checked at compile time:
Shape circle = new Circle();
Shape square = new Square();
//use of polymorphism:
circle.draw();
square.draw();
//downcasting - checked at run time
((Square)square).getCorners();
Downcasting is checked at run-time:if invalid the JVM throws a ClassCastExcption
5.instanceof
The keyword instanceof tells you if an object is an instance of a particular type.
//safe downcast
if(x instanceof Square){
((Square)x).getCorners();
}
Both downcasting and type checking is implemented in Java using the Class class.
阅读(1706) | 评论(0) | 转发(0) |