Code analysis of RTTI and reflection mechanism in Java

RTTI, namely run time type identification. Runtime type recognition is a very useful mechanism in Java. In Java runtime, RTTI maintains class related information. RTTI can automatically recognize each type known at compile time at run time.

In many cases, upward transformation is required. For example, the derived class is derived from the base class, but the existing methods only need to take the base object as a parameter, and the actual input is the reference of its derived class. Then RTTI plays a role at this time. For example, RTTI can identify that the derived class is a derived class of base, so it can be transformed upward to derived. Similarly, when using the interface as a parameter, upward transformation is more commonly used. RTTI can judge whether upward transformation can be carried out at this time.

These type information is completed through the special object of class object (Java. Lang. class), which contains class related information. Whenever a class is written and compiled, a. Class file will be generated to save the class object. The Java virtual machine (JVM) running the program will use the so-called class loader (class loader). The class loader does not load all class objects before the program runs. If it has not been loaded, the default class loader will find the. Class file according to the class name (for example, an additional class loader may look for bytecode in the database). When the bytecode of this class is loaded, it is verified to ensure that it is not damaged and does not contain bad java code. This is also one of the type safety mechanisms in Java. Once the class object of a class is loaded into memory, all objects of that class can be created.

In the above code, the forname method is a static method, and the parameter is the class name, which is used to find out whether the class exists. If found, a class reference will be returned, otherwise a classnotfoundexception exception will be thrown.

If the class is not in the default folder, but in a package, the previous package name needs to be brought, such as TypeInfo Derived。

You can use the getsuperclass method to return the class object corresponding to the base class. Using the newinstance method, you can create an instance object according to the default construction and throw it respectively when it cannot be instantiated and accessed. Instantiationexception and illegalaccessexception exceptions will be thrown.

Java also provides a method to generate references to class objects, that is, class literal constants. For the above program, up is equivalent to base class。

For wrapper classes of basic data types, char Class is equivalent to character Type, int.class is equivalent to integer TYPE。 The remaining ab.class is equivalent to ab.type. (for example, void.class is equivalent to void. Typ). In addition, it is the same thing to start int.class and integer.class in Java se5.

For the generalized class reference, see the following code

A reference to a class < integer > object specifies an integer object, so you cannot point a reference to double class。 To relax restrictions, you can use wildcards?, That is, class , The effect is the same as that of class, but the code is more elegant. Use class Indicates that you did not use a non-specific class reference by accident or negligence. At the same time, you can limit the inherited classes, as shown in the following example

The reason for adding generic syntax to a class reference is simply to provide compile time type checking so that type errors can be found at compile time.

To sum up, the known forms of RTTI include:

1. In traditional type conversion, RTTI ensures the correctness of type conversion. If a wrong type conversion is performed, ClassCastException will be thrown;

2. The class object representing the type of the object can obtain the information required by the runtime by querying the class object (that is, calling the method of the class class).

In C + +, the classic type conversion does not use RTTI. See the RTTI section of C + +. (aside from the topic, I only glanced at the RTTI chapter when I was studying C + +, but now I remember that dynamic_cast is specially added for type safety. C + + can provide selectivity in terms of security, just like Java's StringBuilder and StringBuffer. You can't have both security and efficiency? Java is more mandatory in terms of type security, just like the expression x = 1 can't be used Implicit transformation to boolean type).

The third form of RTTI in Java is the keyword instanceof, which returns a Boolean value to tell whether the object is an example of a specific type. See the following code.

Instanceof can be used to judge some types. For example, the base class shape derives various types (circle, rectangle, etc.). Now a method needs to color all circles, and when inputting parameters, a pile of shape objects. At this time, instandof can be used to judge whether the shape object is a circle object.

RTTI can recognize all classes in the program space, but sometimes it needs to read a string of bytecodes from disk files or network files and be told that these bytes represent a class, so the reflection mechanism needs to be used.

For example, when creating a graphical program in the IDE, some controls will be used. You only need to read from the corresponding class file of the local control, and then actively modify the properties of these controls. (aside: maybe. Net components are like this? I always hear reflections when learning c# but I never feel that I have used them. A few days ago, the classmate who worked on the. Net project also told me that he has never used entrustment and events...)

Class and Java Lang. reflect class library supports the concept of reflection. The class library includes field, method and constructor classes (each class implements the member interface). These types of objects are created by the JVM at runtime to represent the corresponding members in the unknown class.

In this way, you can create unknown objects with constructor, read and modify the fields associated with the field object with get () and set () methods, call the fields associated with the method object with invoke method, and so on.

In short, reflection mechanism is to identify objects of unknown type. Reflection is often used in dynamic proxies. Examples are as follows:

Proxy is one of the basic design patterns, that is, the proxy class is used to provide additional or different operations for the proxy class. The dynamic agent needs a class loader, just as Java needs the class loader to load class information when implementing RTTI, so that you can know the relevant information of the class.

The key methods are:

Object java. lang.reflect. Proxy. newProxyInstance(ClassLoader loader,Class[] interfaces,InvocationHandler h) throws IllegalArgumentException

Pass in three parameters: the loader of the proxy interface (obtained through the getclassloader method of the class object), the proxy method interface, and the proxy object

The first two parameters are well understood, It refers to the loader of the class object (subject) corresponding to the interface of the proxy method and the class object itself, mainly parameter 3. It is necessary to design a class that implements the invocationhandler interface as the proxy object. Generally, the name ends with the handler, and the handler is translated as the handler. It is very vivid. It is the handler that processes instead of the original object Agent is often translated into "handle" in programming.

This class is constructed by passing in a proxy object. For example, the object object is passed in here. The invoke method must then be overridden.

Through the specific implementation of the final output and invoke methods, it can be found that return method invoke(proxied,args); It is equivalent to the original object calling this method (similar to the callback function of C + +)

Because there is a class loader, the proxy object can know the specific class name, method and parameters of the original object. This example outputs these before calling the method.

In practical application, the class name may be selected. For example, there are many classes in the interface. You can selectively process specific classes, methods and parameters

For example, if (proxied instance of realobject) {} or if (method. Getname. Equals ("dosomething") {}

PS: my example has no parameters, so there is no distance

Reference: the fourth edition of Java programming ideas. For more details, see Chapter 14 of the book

summary

The above is all about Java RTTI and reflection mechanism code analysis in this paper. I hope it will be helpful to you.

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
分享
二维码
< <上一篇
下一篇>>