Java Reflection (Java Reflection)

xiaoxiao2021-03-06  117

Reflection is one of the features of the Java program development language, which allows the Java program in the run to check itself, or "self-trial", and can directly operate the internal properties of the program. For example, use it to get the name of each member in the Java class and display it. This capability of Java may not be used in practical applications, but there is no such feature in other programming languages. For example, there is no way to get the function definition related information in the program in PASCAL, C, C . JavaBean is one of the practical applications of Reflection, which allows some tools to visualize the software components. These tools are dynamically loaded and acquired by the REFLECTION. The properties of the Java component (class) are obtained. A simple example considers the following simple example, let's see how the reflection works.

Import java.lang.reflect. *; public class dumpmethods {public static void main (string args []) {try {class c = class.Forname (args [0]); method m [] = c.getDeclaredMetHods (); For (int i = 0; i

Execute as follows: Java DumpMethods Java.util.stack Its result output is: public java.lang.Object java.util.stack.Push (java.lang.object) public synchronized java.lang.Object java.util.stack .POP () public synchronized java.lang.object java.util.stack.peek () public boolean java.util.stack.empty () public synchckronized int java.util.stack.search (java.lang.object) This The method names of the Java.util.stack class are listed, and their restrictions and return types are listed. This program uses class.Forname to load the specified class, then call getDeclaredMethods to get the list defined in this class. Java.lang.Reflect.Method is a class for describing a single method in a class. Start using the reflection used for the class, such as Method, can be found in the java.lang.relfect package. When using these classes, you must follow three steps: The first step is to get the java.lang.class object you want to operate. In the Java program in the run, the classes and interfaces are described with the java.lang.class class. Below is one of the methods of obtaining a Class object: Class C = Class.Forname ("java.lang.string"); this statement gets a class object for a String class. There is another method, as follows: Class C = int.class; or class c = integer.Type; they obtain basic type of class information. The latter method is accessed in the basic type of package class (such as Integer) pre-defined Type fields. The second step is to call a method such as getDeclaredMethods to obtain a list of all methods defined in this class. Once this information is taken, you can perform the third step - use the Reflection API to operate this information, as this code: Class C = Class.Forname ("java.lang.string"); method m [] = C .GetDeclaredMethods (); System.out.println (M [0] .tostring ()); it will print out the prototype of the first method defined in the String in text. In the following example, the three steps will provide an illustration for special applications using the Reflection. After the simulation instanceof operator obtains class information, the next step is to solve some basic problems about the Class object. For example, the class.isinstance method can be used to simulate the InstanceOf operator:

Class a {} public class instance1 {public static void main (string args [= class.forname ("a"); boolean b1 = cls.isinstance (New Integer (37)); system.out .println (b1); boolean b2 = cls.isinstance (new a ()); system.out.println (b2);} catch (throwable e) {system.rr.println (e);}}} in this example A class A class Class A class is created, and then some objects are instances A. Integer (37) is not, but new a () is. Find out how the class is found to find some methods defined in a class, this is a very valuable and very basic reflection usage. The following code achieves this usage:

import java.lang.reflect *;. public class method1 {private int f1 (Object p, int x) throws NullPointerException {if (p == null) throw new NullPointerException (); return x;} public static void main (String args []) {Try {class cls = class.Forname ("Method1"); method method [] = cls.getdeclaredMethods (); for (int i = 0; i

This program first gets the description of the Method1 class, then calls getDeclaredMethods to get a series of Method objects, which describe each method defined in the class, including the public method, protected method, package method, and private methods. If you use GetMethods in the program instead of getDeclaredMethods, you can also get information about each method of inheritance. After obtaining the list of Method objects, it is not difficult to display the parameter types, exception types, and return value types of these methods. These types are basic types or class types, all can be given in order by the objects described. Outputs the result as follows: name = f1decl class = class method1param # 0 class java.lang.Objectparam # 1 intexc # 0 class java.lang.NullPointerExceptionreturn type = int ----- name = maindecl class = class method1param # 0 class [ Ljava.lang.String; Return Type = VOID ---- Gets the usage of the constructor information acquisition class constructor similar to the above acquisition method, such as:

import java.lang.reflect *;. public class constructor1 {public constructor1 () {} protected constructor1 (int i, double d) {} ​​public static void main (String args []) {try {Class cls = Class.forName ( "constructor1"); constructor ctorlist [] = cls.getdeclaredconstructors (); for (int i = 0; i

Import java.lang.reflect. *; public class field1 {private double d; public static final int = 37; string s = "testing"; public static void main (string args []) {try {class cls = Class. Forname ("Field1"); Field FieldList [] = cls.getdeclaredfields (); for (int i = 0; i

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 partpes [] = new class [2]; partypes [0] = integer.Type; Partypes [1] = Integer.Type; method method method ("add", partypes; method2 method = new method2 (); object arglist [] = new object [2]; arglist [0] = new integer (37); arglist [1] = new integer (47); Object retobj = meth.invoke (METHOBJ, Arglist) INTEGER RETVAL = (Integer) Retobj; System.Out.println (RetVal.intValue ());} catch (throwable e) {system.err.println (e);}}} If a program is executing somewhere When you need to perform a method, the name of this method is specified during the running process of the program (for example, this thing in the JavaBean development environment), then the above program demonstrates how to do it. In the above example, getMethod is used to find a method with two integer parameters and namedDD. After finding this method, after the corresponding Method object is created, do it in the correct object instance. When the method is executed, a list of parameters is required, which is two Integer objects that are packaged in the integers 37 and 47 in the previous example. The return of the execution method is also an Integer object, which encapsulates the return value 84. Creating a new object For the constructor, it cannot be performed like the execution method, because the execution of a constructor means creating a new object (accurately, the process of creating an object includes allocating memory and constructive objects). Therefore, the most similar example of the above example is as follows:

Import java.lang.reflect. *; public class constructor2 {public constructor2 () PUBLIC Constructor2 (int A, int b) {system.out.println ("a =" a "b =" b); } Public static void main (string args []) {try {class cls = class.forname ("constructor2"); class party (= new class [2]; partypess [0] = integer.type; partypes [1] = INTEGER.TYPE; Constructor CT = CLS.GetConstructor (Partypes); Object Arglist [] = new object [2]; arglist [0] = new integer (37); arglist [1] = new integer (47); Object Retobj = CT.NEWINSTANCE (arglist);} catch (throwable e) {system.err.println (e);}}} Find the corresponding constructor according to the specified parameter type and execute it to create a new object instance. Using this method can dynamically create objects when running, not when compiling, this is very valuable. Changing the value of the field (domain) REFLECTION is a value that changes the value of the object data field. Reflection can find the field of the object from the running program and change it, the following example can explain this:

Import java.lang.reflect. *; public class field2 {public double d; public static void main (string args []) {try {class cls = class.Forname ("Field2"); Field Fld = CLS.Getfield (" D "); FIELD2 F2OBJ = New Field2 (); System.out.Println (" D = " F2Obj.d); Fld.Setdouble (F2Obj, 12.34); System.out.Println (" D = " F2Obj. d);} catch (throwable e) {system.err.println (e);}}}

In this example, the value of field D is changed to 12.34. The last use of the REFLECTION described using the number of items is to create an array of operations. Array is a special class type in Java language, and a reference to an array can assign an Object reference. See how the following examples look at the array:

Import java.lang.reflect. *; public class array1 {public static void main (string args [= class.forname ("java.lang.string"); Object arr = array.newinstance (CLS) , 10); Array.Set (Arr, 5, "this is a test"); string s = (string) array.get (Arr, 5); system.out.println (s);} catch (throwable e) {System.err.println (e);}}} The String array of 10 units is created, and the value is determined for the character string of the 5th position, and finally, this string gets and printed from the array. . The following code provides a more complex example:

Import java.lang.reflect. *;

Public class array2 {public static void main (string args []) {int Dims [] = new int [] {5, 10, 15}; object arr = array.newinstance (Integer.Type, DIMS); Object Arrobj = array .get (Arr, 3); Class CLS = arrobj.getClass (). getcomponenttype (); system.out.println; arrobj = array.get (Arrobj, 5); array.setint (Arrobj, 10, 37 ); Int Arrcast [] [] [] = (int [] [] []) Arr; System.Out.println (Arrcast [3] [5] [10]);}}} Create a 5 x 10 The integer array of x 15 and the elements of [3] [5] [10] are values ​​37. Note that the multidimensional array is actually an array of arrays, for example, after the first array.get, Arrobj is an array of 10 x 15. Furthermore, one element is obtained, that is, an array of length 15 and assigns an array.setInt to its 10th element. Note that the type when creating an array is dynamic, and does not know the type when compiling. Small junction Java Reflection is very useful, which enables class and data structures to dynamically retrieve relevant information by name, and allow this information to be operated in the running program. This feature of Java is very powerful and is other frequent languages, such as C, C , Fortran or Pascal.

转载请注明原文地址:https://www.9cbs.com/read-98058.html

New Post(0)