Thinking in java-27 Runtime Type Identification运行时类型确定

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值