1. Functions of the Java reflection mechanism
In the Java Runtime Environment, can I know the attributes and methods of any class? For any
Can an object call any of its methods? The answer is yes. This kind of dynamic retrieval class information and dynamic
The function of calling an object method comes from the reflection mechanism of the Java language. Java reflection mechanism mainly provides
Has the following features:
L determine the class to which any object belongs during running;
L construct objects of any class at runtime;
L judge the member variables and methods of any class at runtime;
L call methods of any object at runtime;
L generate a dynamic proxy.
This chapter first introduces the usage of Java reflection API, and then introduces an example of remote method call.
In this example, the client can remotely call a method of an object on the server. The server uses the reflection mechanism to provide
The client uses the dynamic proxy function provided by the reflection mechanism.
2. Several important classes involved in Java reflection are located in the Java. Lang. Reflect package.
Class class: represents a class. to operate a class through reflection, you must create a Class Object Based on the specified class.
Method class: represents the methods in the class. to operate a method, java. Lang. Reflect provides the method class, you can create a specified
The method object of the method. This object represents this method, which also reflects the idea that everything is an object.
Field Class: represents the member variables of the class.
Constructor class: indicates the constructor class. It is not parsed here, because it can be understood as a method class.
Array class: Used to dynamically create arrays and access array elements
3
. Use the three steps of the class in the Java. Lang. Reflect package
1. Get a java. Lang. Class object, which is obtained by specifying the class you want to operate. Java. Lang. Class is used as the representative class and interface (
The first step is to obtainjava.lang.Class
Object for the class that you want to manipulate.java.lang.Class
Is used to represent classes and interfaces in a running Java program.
).
There are three methods to obtain the java. Lang. Class Object:
One way of obtaining a class object is to say:
Class C = Class. forname ("Java. lang. string "); <br/> to get the Class Object for string <br/> another approach is to use: <br/> Class C = int. class; <br/> or <br/> Class C = integer. type; </P> <p>
2. Obtain class information, such as method, field, constructor (the second step is to call a method suchgetDeclaredMethods
, To get a list of all the methods declared by the class .).
3. After obtaining information, use the reflection API to perform operations on the information (once this information is in hand, then the third step is to use
Reflection API to manipulate the information. For example ).
4. Understanding of the invoke method in the method class
Method (Java 2 platform SE 6)
Invoke <br/> Public objectinvoke (Object OBJ, object... ARGs) throws illegalaccessexception <br/>, illegalargumentexception <br/>, invocationtargetexception <br/>
This interface is used to call a specified object with specified parameters.Method
The underlying method of the object. Some parameters are automatically decompressed to match the basic parameters. Both basic parameters and reference parameters are subject to method call conversion as needed.
-
If the underlying method is static, you can ignore the specifiedobj
Parameters. This parameter can be null.
If the shape parameter required by the underlying method is 0args
The array length can be 0 or null.
If the underlying method is an instance method, dynamic method lookup is used to call it. This is recorded in Java language specification, Second Edition
In section 15.12.4.4 of; this should be done in the case of a rewrite of the runtime type based on the target object.
If the underlying method is static and the class that declares this method has not been initialized, it will be initialized.
If the method completes normally, the value returned by the method is returned to the caller. If the value is of the basic type, it is first packaged in the object as appropriate. However, if the value type is a set of basic types, the array elementNo
Wrapped in an object; in other words, an array of the basic type is returned. If the underlying method returns the void type, the call returns NULL.
-
-
-
Parameters:
-
obj
-The object from which the underlying method is called
-
args
-Parameters used for method call
-
Return Value:
-
Parameters Used
args
In
obj
Specifies the result of the method indicated by this object.
-
Throw:
-
IllegalAccessException
-IfMethod
The object enforces Java access control, and the underlying method is not accessible.
-
IllegalArgumentException
-
If the method is an instance method and the specified object parameter is not an instance of the class or interface (or its subclass or implementation program) that declares the underlying method, if the number of real parameters and form parameters is different; if the unpackage conversion of basic parameters fails, if the unpackage is canceled, the parameter value cannot be converted to the corresponding parameter type through method call conversion.
-
InvocationTargetException
-If the underlying method throws an exception.
-
NullPointerException
-If the specified object is null, this method is an instance method.
-
ExceptionInInitializerError
-If initialization fails due to this method.
-
Let's look at a specific example of this method:
-
import java.lang.reflect.*; public class method2 { public int add(int a, int b) { return a + b; } public static void main(String args[]) { try { Class cls = Class.forName("method2"); Class partypes[] = new Class[2]; partypes[0] = Integer.TYPE; partypes[1] = Integer.TYPE; Method meth = cls.getMethod( "add", partypes);(1) method2 methobj = new method2();(2) Object arglist[] = new Object[2]; arglist[0] = new Integer(37); arglist[1] = new Integer(47); Object retobj = meth.invoke(methobj, arglist);(3) Integer retval = (Integer)retobj; System.out.println(retval.intValue()); } catch (Throwable e) { System.err.println(e); } } }
-
(1) create an object for the specified method, and (2) Call the underlying method represented by the object
-
Here we need to have a thought transformation. We created a method2 object in (2). According to our habits, all the methods called by XX are methobj. XX () is called in this way, but we cannot call this method after reflection is used. Instead, this object is treated as a parameter.
-
First, let's take a look at the explanation of the invoke method: to call a specified object with a specified parameter from this
Method
The underlying method of the object.
-
Analysis: Object retobj = meth. Invoke (methobj, Arglist );
-
The result of this statement is that the add method is called, but you do not know how to call it directly. "The specified object with the specified parameter" here refers to methoject And Arglist, "This method object" indicates meth. The call method turns into a bend. In short, we must turn our thinking into a new one when using this method. At this time, we no longer need to manually specify the call method, instead, the program automatically calls the method to be called by passing in the subject object and parameters.