On the concepts of Java RTTI and reflection

1、 Concept

RTTI (run time type identification) means to identify the type of an object at runtime, and its corresponding class is a class object. How to understand this class object? If a class is a collection of all object methods and attributes, you can understand this class object as a collection of all classes, and then use this class object to dynamically resolve it Relevant classes can be found, and their constructors and methods can be obtained, and even the objects of this class can be instantiated. Before starting this article, I would like to mention an important point: whether RTTI or reflection, their essence is the same. They all dynamically obtain class information. The only difference between them is:

2、 RTTI

There are two ways to get a class object:

It can be seen that using RTTI, you must know the name of the class when writing the program in order to obtain the reference of the class object to this class, and use this reference to get a lot of information about this class, including interfaces, parent classes, methods, static members, and even a way to implement "virtual constructor" such as newinstance () method.

In addition, a call that often uses the instanceof keyword actually uses the class object and returns a Boolean value.

3、 Reflection

Sometimes in Java, the class to be processed appears long after the compiler generates code for the program. How can we deal with this class at this time, that is, we can't know the class of this object at compile time. The answer is to use Java's reflection mechanism. No more nonsense. After reading the following code, you will clearly understand the difference between RTTI and reflection.

How to bring in parameters in the main method can refer to this blog. I use the native javac - encoding UTF-8 RTTI Java and Java RTTI com jomoo. test. seven. An error is reported when actioncharacter runs: error: could not find or load main class RTTI, my JDK is poisonous! But with the help of powerful ide tools:

4、 Summary

In fact, the concept of RTTI was only mentioned in thinking in Java, which attracted so many people's discussion. There is no such concept in native Java. Therefore, we don't have to worry about RTTI or reflection at all. They are the same in both usage and essence. They are all for the same purpose - to dynamically obtain class information. We should focus on use rather than on differences.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>