Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Or it depends on the actual situation?

like image 728
gdlamp Avatar asked May 14 '13 22:05

gdlamp


2 Answers

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.

Hope this helps!

like image 85
templatetypedef Avatar answered Sep 23 '22 00:09

templatetypedef


In short, the true difference between RTTI and reflection is that with RTTI, the compiler opens and examines the .class file at compile time. With reflection, the .class file is unavailable at compile time; it is opened and examined by the runtime environment.

like image 40
Igor G. Avatar answered Sep 23 '22 00:09

Igor G.