Java Rtti mechanism and reflection mechanism

Source: Internet
Author: User

1.1 What is Rtti?

Wikipedia definition: In computer programming, RTTI (run-time type information, or run-time type identification) refers to a C + + Mechani SM that exposes information about an object's data type at runtime. Run-time type information can apply to simple data types, such as integers and characters, or to generic types. This is a C + + specialization of a more general concept called type introspection.

Run-time type information allows you to discover and use type information while the program is running. Runtime type information (RTTI) allows you to discover and use type information while a program is running.

In short: When you have a reference to a base class object, you can use Rtti to query the exact type of the object referenced by the reference.

There are two ways in Java that let us identify objects and classes at run time:

(1) Traditional rtti: It assumes that we already know all the types at compile time ;

(2) Reflection mechanism: It allows us to discover and use class information at runtime .

1.2 Why do I need Rtti?

It is often necessary to know the variable of a reference type (in order to take advantage of polymorphism, it is generally a generalization reference, that is, a reference variable to the parent class) that refers to the concrete type of the object, so that the specific operation can be done differently depending on the type. Using Rtti can help us determine the exact type of object referenced by a generalization reference.

It is generally the following process: Judge the specific type of reference variable → convert to a specific type → perform a special type-related operation.

1.3 How does type information in Java be represented at run time?

This is represented by a class object, which contains information about the class. Java uses the class object to perform its rtti, even if you are doing something like a conversion. (Java performs its RTTI using the Class object, even if you ' re doing something like a cast.)

2.1 The traditional RTTI

Strictly speaking, reflection is also a form of rtti, however, the general documentation of RTTI and reflection separate, because generally, we think rtti refers to the traditional rtti.

3 forms of Rtti used in Java (known as Rtti form in Java)

(1) Traditional type conversion

For example "(type)", the correctness of the type conversion is ensured by Rtti, and if an incorrect type conversion is performed, the classcastexception is thrown. In Java, all type conversions are run for correctness checks. Therefore, you need to identify the type of an object at run time. Note that type conversions in C + + do not use Rtti.

Traditional rtti are implemented in the form of transformations or instanceof (that is, in the form of instanceof or isinstance (), but all need to specify the type to be transformed, such as:

     Public void rtti (Object obj) {        = (Orange) obj;    // while obj is being transformed, in the compile time, you need to know the type of orange that you want to turn into, which is the. class        file that needs orange. // Class clazz = Class.forName ("Rtti. Orange ");     // In contrast, reflection completely determines the type at run time through class classes, without the need to load the Orange. class file in advance.     }

(2) Class object representing the object type

The

Queries the class object to get the information required by the runtime. ( Class class object cast rtti ). In fact, there is no essential difference between reflection and Rtti, because Java classes are loaded and parsed on the run, and both get type information through the class object. Only types that Rtti can maintain are types that are known at compile time, and reflection can use some types that are completely unknown at compile time.

        Class clazz = Orange. class;    // get Class object, Orange This class must be compile-        time known System.out.println (Clazz.getname ());    // obtain various types of information using class correspondence         System.out.println (Clazz.gettypename ());        System.out.println (Clazz.getsuperclass ());        System.out.println (Clazz.isinterface ());

(3) instanceof or class.isinstance ()

Traditional rtti are implemented in the form of transformations or instanceof (that is, in the form of instanceof or isinstance (), but all need to specify the type to be transformed, such as:

        if instanceof Apple) {    //Apple This class must be compile-time, and the compiler will open and check Apple's corresponding. class file             ((Apple) x) at compile time. info ();                X.getclass (). isinstance (apple); // The class that declares the Apple object must be compile-time-agnostic

The difference between 2.2 RTTI and reflection

The use of Rtti must satisfy a condition: if you want to know the exact type of a generalization reference, then this class must be known at compile time.

The exact type of an object can be queried by RTTI, which must be known at compile time (either a class in the System class library or a class that you define in your own code). Because a class definition will eventually be converted to a. class file, the compiler will go to look for a corresponding. class file, without the error "errors: no symbols found", which is done during the compile phase, so that you can use Rtti to identify it. In other words, at compile time, the compiler must know all the classes to be handled by RTTI.

The difference between Rtti and reflection is as follows:

RTTI: The *.class file is opened and inspected by the compiler at compile time .

Reflection mechanism: The *.class file is opened and inspected by the JVM at run time .

            Class clazz1 = Class.forName ("Rtti. Apple ");    // The compiler does not check and open the string "Rtti" during the compile phase. The. class file that is specified by Apple, but is loaded by the JVM during run time.             System.out.println (Clazz1.getname ());    
        New Bnana ();    // The compile-time compiler will look for the respective. class files for the fruit class and the Apple class.         Class clazz2 = fruit.getclass ();        System.out.println (Clazz2.getname ());

Question: What exactly did the compiler do in the process of opening and inspecting the *.class file at compile time?

3.1 Reflection mechanism

Wikipedia definition: In computer science, reflection are the ability of a computer program to examine (see type introspection) and modif Y The structure and behavior (specifically the values, Meta-data, properties and functions) of the program at runtime.

Not all types can be determined at compile time (for example, a program that has input a class name that shows all the methods of the Class), so the work of opening and checking the. class file is pushed to the runtime for processing. Typical scenarios are "component-based programming" and remote Method invocation (RMI).

The results generated by Class.forName () are not known at compile time, that is, compile-time does not verify that the class that corresponds to the parameter string exists. This is handled by the JVM at run time, so this method throws ClassNotFoundException.

Class supports reflection by including the Field/method/constructor class in Java.lang.reflect and each class implements the member interface. These types of objects are created by the JVM at run time to represent the corresponding members in the unknown class. If you can create new objects with the constructor class, use the Get () and set () methods to read and modify the fields associated with the Field object, and invoke the method associated with the methods object with the Invoke () method. You can also call GetFields (), GetMethods (), GetConstructors (), and so on to return an array of objects that represent fields, methods, and constructors. Thus, the class information of an unknown object can be fully determined at run time, and no information needs to be known at compile time.

3.2 How to get a class object

(1) class.forname (String packagenameplusclassname);

(2) Object.getclass ();

(3) class literal constants

3.3 Generalization of class references

(1) Wildcard mode

class<?> intclass  int.  Class;

(2) Extends realization scope limit

extends int. class;

(3) Super Mode

Class<apple> Apclass = Apple. class  = apclass.newinstance (); ClassSuper fruit> up = Apclass.getsuperclass ();

Equivalence of 3.4 instanceof and class

(1) instanceof and isinstance () produce exactly the same results as equal and = =.

(2) instanceof and isinstance () maintain the concept of type, which refers to "are you a class or a derived class of this class?" ”

(3) equal and = = The actual class object, regardless of inheritance-it is either the exact type, or not.

4. Summary

Java programming ideas, the 14th chapter at the end of the summary section:

The 1th paragraph means that using RTTI, you can find the exact type of the reference variable and then perform the corresponding operation (like the switch statement, P327 example) based on the exact type of the reference variable. In this way, polymorphism is not used and the value of polymorphism is lost. So try to use polymorphic mechanisms, just use rtti when necessary.

第2-4, this paper summarizes the advantages of rtti in some scenes, and illustrates the problems that can be solved by using rtti respectively.

Resources

Java programming Idea, 14th chapter, 8th Chapter 8.5.2

Http://www.cnblogs.com/zhguang/p/3091378.htm

http://blog.csdn.net/cannel_2020/article/details/7226108

http://blog.csdn.net/a81895898/article/details/8457623

Http://blog.sina.com.cn/s/blog_548c8a8301013j6u.html

Java Rtti mechanism and reflection mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.