RTTI的定义
RTTI(Run-Time Type Identification 运行时类型识别):程序能够使用基类的指针或引用来检查这些指针或引用所指的对象的实际派生类型。(定义来自百度百科)。
RTTI在Java中的工作原理
Java中有一个特殊的对象——Class,它包含了与类相关的信息。Class对象可以用来创建类的所有“常规对象”。Java用Class对象来执行其RTTI。
下面这个类中的getInheritanceSys(Object obj)方法可以接受任意对象作为参数,打印该对象所在继承体系中的所有类名:
package com.cjjcsu.chapter2;
import java.awt.List;
/**
* 打印任意对象的继承关系
* @author Jeslie
*
*/
public class InheritanceInfo {
private void getInheritanceSys (Object obj){
int i = 1;
System.out.println("\""+obj.getClass().getCanonicalName()+"\"的继承体系:");
System.out.println(i+":"+obj.getClass().getCanonicalName());
try {
Class> class1 = Class.forName(obj.getClass().getCanonicalName());
if(class1.getSuperclass()==null) {
return;
}
do{
System.out.println("↓ 继承自");
System.out.println(++i+":"+class1.getSuperclass().getCanonicalName());
class1 = Class.forName(class1.getSuperclass().getCanonicalName());
}while((class1.getSuperclass()!=null));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
InheritanceInfo info = new InheritanceInfo();
info.getInheritanceSys(new List());//取得要打印继承关系的对象
}
}