Java Reflection (Java Reflection)

xiaoxiao2021-03-06  70

Java Reflection (JAVA reflection) Author: corlin Date: 04-05-10 10:32 Hits: 748 Reflection is one of the characteristics of the development of the Java programming language, which allows a Java program running on their own inspection, or "self Review, 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. 1. A simple example considers the following simple example, let us 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

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 instanceof operators: class a {} public class instance1 {public static void main (string args []) {try args []) {Try {class cls = 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);}}} Class A class object in this example is created, and then check if some objects are instances A. Integer (37) is not, but new a () is. 3. Find out how the class is found to find something defined in a class, which is a very valuable and very basic reflection usage.

The following code is implemented: 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

The result of the output is as follows: Name = f1 decl class = class method1 param # 0 class java.lang.object param # 1 int exc # 0 class java.lang.nullpointersException return..NULLPOINTEREXCEPTION RETURN TYPE = INT ----- name = main decl class = Class method1 param # 0 class [ljava.lang.string; return type = void ----- 4. Get 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

The result of this program is: name = constructor1 decl class = class constructor1 ----- name = constructor1 decl class = Class Constructionor1 param # 0 int param # 1 double ----- 5. Get class field (domain) Find out which data fields defined in a class are also possible. The following code is doing this: import java.lang.reflect. *; Public class field1 {private double d; public static final int i = 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 < FieldList.Length; i ) {Field FLD = FieldList [i]; system.out.println ("name =" fld.getname ()); system.out.println ("decl class =" fld.getDeclaringclass () ); System.out.println ("type =" fld.gettype ()); int mode = fld.getmodifiers (); system.out.println ("Modifiers =" Modifier.Tostring (MOD)); System. Out.println ("-----");}} catch (throwable e) {system.err.println (e);}}} This example is very similar to the previous example. The example uses a new thing Modifier, which is also a reflection class that describes the modifiers of the field member, such as "Private Int". These modifications themselves are described by integer, and using modifier.tostring to return string descriptions arranged in "official" sequential order (such as "Static" before "Final").

The output of this program is: name = d decl class = class field1 type = double modifiers = private ----- name = i decl class = class field1 type = int modifiers = public static final ----- name = s DECL Class = Class Field1 Type = Class Java.lang.string MODIFIERS = ------- and get the method of getting the method, you can only get the field information (getDeclaredfields) declared in the current class when you get the field. Get the field defined in the parent class (getFields). 6. Execute method text from the name of the method to here, and there is no exception to how to obtain information about how to acquire the class. We can also use reflection to do some other things, such as implementing a method specified by a name. The following example demonstrates this operation: 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 method = CLS.GetMethod "add", pieys); method2 methobj = 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 knows a certain method when it is executed, the name of this method is specified during the running process of the program (for example, there is such a thing in the JavaBean development environment), then the above program Demonstrate 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.

7. Creating a new object For the constructor, it cannot be performed as in the implementation 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). So, 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]; partypash 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. 8. Change the value of the field (domain) REFLECTION has a use of the value to change 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 the field d, the value of field D is changed to 12.34.

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

New Post(0)