The concept of runtime type identification (rtti, run-time type identification) initially looks very simple: when you only
When you reference a base class pointing to an object, the rtti mechanism allows you to find the exact type of the object.
The need for rtti reveals many interesting (and complex) problems in object-oriented design.
Organization Program problems.
This article discusses how Java allows us to identify object and class information at runtime. There are two main methods:
It is a traditional rtti, which assumes that we know all the types during the compilation and runtime; the other is the reflection machine.
(Reflection) ", which allows us to get class information at runtime. Let's first discuss the "traditional" rtti, and then discuss
Reflection.
Java implements the rtti mechanism through class objects, even if we only need to do something like type conversion
Situation. The class also provides many other ways for us to use rtti.
First, you need to obtain a reference pointing to an appropriate class object. One way is to use a string
The class. forname () method is as demonstrated by the example. This method is very convenient, because you are getting clas
Does not need to generate objects of the class type. However, if you already have
You can call getclass () to obtain the class reference. This is the root class objec.
Provided. It returns a class reference to indicate the actual type of the object. Class provides some interesting
The following example shows the Methods:
Rtti allows you to discover type information by referencing anonymous base classes. Beginners can easily misuse it because they learn to use more
This method is also effective before calling the method. For many people with procedural programming backgrounds, it is difficult for them
It is organized into a series of switch statements in sequence. They may use rtti to do this, but in this way, code development and
The important value of the polymorphism mechanism is lost during maintenance. Java requires that we always use the polymorphism mechanism, only when necessary
When rtti is used.
However, the method call using the polymorphism mechanism requires us to have control over the definition of the base class, because when you expand the program,
You may find that the base class does not contain the method we want. If the base class comes from a library or is controlled by someone else
Rtti is a solution: You can inherit a new class and then add the method you need. Elsewhere in the code,
You can identify your own specific classes and call your own methods. This will not disrupt polymorphism and program scalability.
Force, because you do not need to search for the switch statement in the program to add a new class. However, if you
To add the new feature code you need, you must use rtti to check your specific class.