您的位置:首页 > 编程语言 > Java开发

Java 深入学习(23) —— RTTI 和 反射 的区别

2018-01-17 09:09 471 查看
术语
“RTTI”
是一个特定于C ++的术语,指的是核心语言的功能——“它允许程序在运行时确定各种对象的动态类型。”

术语
“反射”
是跨程序语言使用的通用术语,指的是程序在运行时检查和修改其对象,类型等的能力。

The term "RTTI" is a C++-specific term referring to the functionality of the core language that allows the program to determine the dynamic types of various objects at runtime. It usually refers to the dynamic_cast or typeid operators, along with the associated std::type_info object produced by  typeid.

The term reflection, on the other hand, is a generic term used across programming languages to refer to the ability of a program to inspect and modify its objects, types, etc. at runtime.

The term I've heard applied to instanceof is type introspection and instanceof is sometimes referred to as object introspection, as the program is allowed to look at the running types to determine what course of action to take. I think this is a weaker term than reflection, as it doesn't allow for elaborate introspection on the fields or methods of an object, but I don't think it would be technically incorrect to call the use of the instanceof operator reflection.

As to your other question - how does class information get loaded at runtime? - that's really up to the JVM implementation. The ClassLoader type is ultimately responsible for loading classes into the system, but the JVM can interpret this however it wants to. I once built a prototype JVM in JavaScript, and internally all reflection calls just queried the underlying JS data structures I had in place to represent classes, fields, and methods. I would imagine that the HotSpot JVM does something totally different, but it's pretty much implementation-defined.


Java RTTI的说法其实有点别扭。Java官方文档 - Java Platform SE 7 从来没有这个说法。都直接叫“Reflect”,或者“Reflection API”

Oracle官方文档对“反射”的描述是这样:

Provides classes and interfaces for obtaining reflective information about classes and objects. Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use of reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.


所以java的反射机制不但能够在运行时获得对象和类型的信息,而且还能动态加载类,动态访问以及调用目标类型的字段,方法以及构造函数。

所以RTTI和反射是两个不同体系在描述同一件事情。

RTTI对应C++体系,反射对应OO面向对象体系。

只不过,两者是用的完全不同的两套实现方法。而且相比较而言,Java的反射机制功能比C++的RTTI更完整一些(但按Chris的说法,java的反射也不彻底。)。

Difference between RTTI and reflection in Java

https://stackoverflow.com/questions/16553836/difference-between-rtti-and-reflection-in-java

Java RTTI和反射的区别?

https://www.zhihu.com/question/21080782
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: