简体   繁体   English

Java中RTTI与反射的区别

[英]Difference between RTTI and reflection in Java

My question is when how does the class info gets loaded during runtime? 我的问题是在运行时如何加载类信息?

When someone calls instanceof is that considered RTTI or reflection? 当有人调用instanceof是考虑RTTI还是反思? Or it depends on the actual situation? 还是取决于实际情况?

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. 术语“ RTTI ”是一个特定于C ++的术语,指的是核心语言的功能,它允许程序在运行时确定各种对象的动态类型。 It usually refers to the dynamic_cast or typeid operators, along with the associated std::type_info object produced by typeid . 它通常引用dynamic_casttypeid运算符,以及由typeid生成的关联std::type_info对象。

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. 我听过应用于instanceof的术语是类型内省,instanceof有时被称为对象内省 ,因为允许程序查看运行类型以确定要采取的操作过程。 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. 我认为这是一个比反射更弱的术语,因为它不允许对对象的字段或方法进行详细的内省,但我认为在操作中使用instanceof运算符反射在技术上并不正确。

As to your other question - how does class information get loaded at runtime? 至于你的另一个问题 - 如何在运行时加载类信息? - that's really up to the JVM implementation. - 这完全取决于JVM的实现。 The ClassLoader type is ultimately responsible for loading classes into the system, but the JVM can interpret this however it wants to. ClassLoader类型最终负责将类加载到系统中,但JVM可以解释它想要的。 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. 我曾经用JavaScript构建了一个原型JVM,并且在内部所有的反射调用都只查询了我用来表示类,字段和方法的底层JS数据结构。 I would imagine that the HotSpot JVM does something totally different, but it's pretty much implementation-defined. 我认为HotSpot JVM做了一些完全不同的事情,但它几乎是实现定义的。

Hope this helps! 希望这可以帮助!

In short, the true difference between RTTI and reflection is that with RTTI, the compiler opens and examines the .class file at compile time. 简而言之,RTTI和反射之间的真正区别在于,使用RTTI,编译器会在编译时打开并检查.class文件。 With reflection, the .class file is unavailable at compile time; 使用反射,.class文件在编译时不可用; it is opened and examined by the runtime environment. 它由运行时环境打开并检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM