1. RTTI
这里有关于RTTI详细的pdf文件。
RTTI lets you find the exact type of an object when you only have a reference to the base type.
RTTI is used to reveal the true types at run time.
运行时类型鉴定RTTI能使得在运行时确定对象的确切类型成为可能。
2. RTTI vs Reflection API
• With RTTI we need to have all the types we use at
run time available at compile time
• Many times this is not possible:
• If we receive data that represents classes remotely, at
compile time we do not have them
• e.g. with Remote Method Invocation (RMI) we can call methods distributed on remote machines. Locally at compile time, we do not know the types used by these methods
运行时类型检验RTTI的条件是:我们需要在运行时使用的类型必须满足在编译时可用。但是这个条件有时并不能满足:比如RMI,Remote Method Invocation.
但是java中的反射机制Reflection机制就没有这些限制了,Reflection下部分讲。
3 . Demo
类型转换,含upcast和downcast是RTTI的一个具体例子。
package com.fqyuan.thinking;
class Useful {
public void foo() {
}
}
class MoreUseful extends Useful {
@Override
public void foo() {
}
public void bar() {
}
}
public class RTTI {
public static void main(String[] args) {
Useful[] arr = { new Useful(), new MoreUseful() };
arr[0].foo(); // Ok
arr[1].foo(); // Ok
// Compile-time error
// arr[1].bar();
((MoreUseful) arr[1]).bar(); // Ok, explicit downcast
// Compile-time ok, but java.lang.ClassCastException
((MoreUseful) arr[0]).bar();
}
}
//Running result:
Exception in thread "main" java.lang.ClassCastException: com.fqyuan.thinking.Useful cannot be cast to com.fqyuan.thinking.MoreUseful
at com.fqyuan.thinking.RTTI.main(RTTI.java:31)