USING JAVA REFLECTION

xiaoxiao2021-03-06  91

USING JAVA REFLECTION

Print-Friendly Version

Articles IndexBy Glen McCluskeyJanuary 1998 Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them. The ability to examine and manipulate a Java class from within itself may not sound like very much, but in other programming languages ​​this feature simply does not exist. For example, there is no way in a Pascal, C, or C program to obtain information about the functions defined within that program. One tangible use of reflection is in JavaBeans, where software components can be manipulated visually via a builder tool. The tool uses reflection to obtain the properties of Java components (Classes) As the is. A Simple Example To See How Reflection Works, Consider this Simple Example:

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

System.out.println (M [i] .tostring ());

}

Catch (throwable e) {

System.err.Println (e);

}

}

}

For An Invocation of: Java Dumpmethods Java.util.stack

The 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 synchronized

INT java.util.stack.search (java.lang.object)

That is, the method names of class java.util.Stack are listed, along with their fully qualified parameter and return types. This program loads the specified class using class.forName, and then calls getDeclaredMethods to retrieve the list of methods defined in the class. java.lang.reflect.Method is a class representing a single class method. Setting Up to use Reflection The reflection classes, such as Method, are found in java.lang.reflect. There are three steps that must be followed to use these classes. The first step is to obtain a java.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. One way of obtaining a class object IS to SAY: CLASS C = Class.Forname ("java.lang.string"); to get the class object for string. another approach is to use: class c = int.class;

Or class c = integer.Type;

to obtain Class information on fundamental types. The latter approach accesses the predefined TYPE field of the wrapper (such as Integer) for the fundamental type. The second step is to call a method such as getDeclaredMethods, to get a list of all the methods declared By The Class. Once This Information IS in Hand, THEN THIRD Step is To Use the Reflection. for Example, The Sequence: Class C = Class.Forname ("java.lang.string");

Method m [] = c.getdeclaredMethods ();

System.out.println (M [0] .tostring ());

will display a textual representation of the first method declared in String. In the examples below, the three steps are combined to present self contained illustrations of how to tackle specific applications using reflection. Simulating the instanceof Operator Once Class information is in hand, often the NEXT Step is to ask Basic Questions About The Class Object. for Example, The Class.Isinstance Method Can Be Used To Simulate The InstanceOf Operator: Class A {}

Public class installation1 {

Public static void main (string 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.err.Println (e);

}

}

}

In this example, a Class object for A is created, and then class instance objects are checked to see whether they are instances of A. Integer (37) is not, but new A () is. Finding Out About Methods of a Class One Of The Most Valuable and Basic Uses of Reflection Is To Find Out What Methods Are Defined Withnin A Class. To do this The Following Code Can Be Used:

Import java.lang.reflect. *;

Public class method1 {

Private Int F1

Object P, Int x) THROWS NULLPOINTEREXCEPTION

{

IF (p == NULL)

Throw new nullpointerserException ();

Return X;

}

Public static void main (string args [])

{

Try {

Class CLS = Class.Forname ("Method1");

Method metlist []

= CLS.GetDeclaredMethods ();

For (int I = 0; i

i ) {

Method M = Methlist [i];

System.out.println ("Name

= " m.getname ());

System.out.println ("DECL Class ="

M.GetDeclaringClass ());

Class PVEC [] = M.GetParameterTypes (); for (int J = 0; J

System.out.println ("

Param # " J " " PVEC [J]);

Class EVEC [] = M.GETEXCEPTIONTYPES ();

For (int J = 0; j

System.out.println ("EXC #" J

"" EVEC [J]);

System.out.Println ("Return Type ="

M.Getreturntype ());

System.out.println ("-----");

}

}

Catch (throwable e) {

System.err.Println (e);

}

}

}

The program first gets the Class description for method1, and then calls getDeclaredMethods to retrieve a list of Method objects, one for each method defined in the class. These include public, protected, package, and private methods. If you use getMethods in the program instead of getDeclaredMethods, you can also obtain information for inherited methods. Once a list of the Method objects has been obtained, it's simply a matter of displaying the information on parameter types, exception types, and the return type for each method. each of these Types, WHETHER THEY ARE FUNDAMENTAL or CLASS TYPES, IS IN TURN REPRESENTED BY A Class Descriptor. The Output of The Program IS:

Name = f1

DECL Class = Class Method1

PARAM # 0 Class Java.lang.Object

Param # 1 int

EXC # 0 Class Java.lang.NullPointersRexception

Return Type = INT

-----

Name = main

DECL Class = Class Method1

Param # 0 class [ljava.lang.string;

Return Type = Void

-----

Obtaining Information About Constructors A Similar Approach IS Used to Find Out About The Constructors of a class. For example:

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

Constructor CT = CTORLIST [I];

System.out.println ("Name

= " ct.getname ());

System.out.println ("DECL Class ="

Ct.getDeclineClass ());

Class PVEC [] = ct.getParameterTypes ();

For (int J = 0; j

System.out.println ("Param #"

J " PVEC [J]);

Class EVEC [] = ct.getexceptiontypes ();

For (int J = 0; j

System.out.println (

"EXC #" J " EVEC [J]);

System.out.println ("-----");

}

}

Catch (throwable e) {

System.err.Println (e);

}

}

}

There Is No Return-Type Information Real Real, Constructors Don't Real, When This Program is Run, The Output IS:

Name = constructor1

DECL Class = Class Constructor1

-----

Name = constructor1

DECL Class = Class Constructor1

Param # 0 int

Param # 1 double

-----

Finding Out About Class Fields It's Also Possible To Find Out Which Data Fields Are Defined in a class. To do this, the following code can be used:

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

System.out.println ("Name

= " fld.getname ());

System.out.println ("DECL Class ="

Fld.getDeclaringClass ());

System.out.println ("TYPE

= " fld.gettype ());

Int mod = fld.getmodifiers ();

System.out.println ("MODIFIERS ="

Modifier.toString (MOD));

System.out.println ("-----");

}

}

Catch (throwable e) {

System.err.Println (e);

}

}

}

This example is similar to the previous ones. One new feature is the use of Modifier. This is a reflection class that represents the modifiers found on a field member, for example "private int". The modifiers themselves are represented by an integer, and Modifier.tostring is buy to return a string representation in the "official" declaration Order (Such AS "static" before "final"). The Output of the 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 =

-----

As with methods, it's possible to obtain information about just the fields declared in a class (getDeclaredFields), or to also get information about fields defined in superclasses (getFields). Invoking Methods by Name So far the examples that have been presented all relate to Obtaining class information. but it's also picture, for example to invoke a method of a specified name. To Seeh How this Works, Consider The Following Example:

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);

}

}

}

Suppose that a program wants to invoke the add method, but does not know this until execution time. That is, the name of the method is specified during execution (this might be done by a JavaBeans development environment, for example). The above program shows a way of doing this. getMethod is used to find a method in the class that has two integer parameter types and that has the appropriate name. Once this method has been found and captured into a Method object, it is invoked upon an object instance of the appropriate type. To invoke a method, a parameter list must be constructed, with the fundamental integer values ​​37 and 47 wrapped in Integer objects. The return value (84) is also wrapped in an Integer object. Creating New Objects There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction). So the nearest equi Valent to the prepvious example is to say: 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 Partypes [] = new class [2];

Partypes [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);

}

}

}

which finds a constructor that handles the specified parameter types and invokes it, to create a new instance of the object. The value of this approach is that it's purely dynamic, with constructor lookup and invocation at execution time, rather than at compilation time. Changing values ​​of Fields Another use of reflection is to change the values ​​of data fields in objects. The value of this is again derived from the dynamic nature of reflection, where a field can be looked up by name in an executing program and then have its value THIS ILLUSTRATED by The Following Example: 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 d field has its value set to 12.34. Using Arrays One final use of reflection is in creating and manipulating arrays. Arrays in the Java language are a specialized type of class, and an array reference can be assigned to an Object Reference. To Seeh How Arrays Work, Consider The Following Example:

Import java.lang.reflect. *;

Public class arrAy1 {

Public static void main (string args [])

{

Try {

Class CLS = 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);

}

}

}

.. This example creates a 10-long array of Strings, and then sets location 5 in the array to a string value The value is retrieved and displayed A more complex manipulation of arrays is illustrated by the following code: 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 (CLS);

Arrobj = array.get (Arrobj, 5);

Array.setint (Arrobj, 10, 37);

Int Arrcast [] [] = (int [] [] []) Arr;

System.out.println (Arrcast [3] [5] [10]);

}

}

This Example Creates A 5 x 10 x 10 x 10 x 10] [5] [10] in the array to the value 37. Note Here That A Multi-Dimensional Array Is Actually An Array Of Arrays , SO That, for example.get, the result in arrobj is a 10 x 15 Array. this is peeled back overce again to Obtain A 15-long array, and the 10th slot in That Array Is Set Using Array .setInt. Note that the type of array that is created is dynamic, and does not have to be known at compile time. Summary Java reflection is useful because it supports dynamic retrieval of information about classes and data structures by name, and allows for their Manipulation Withn Executing Java Program. This Feature IS Extreme Powerful and Has No Equivalent in Other Conventional Languages ​​Such AS C, C , Fortran, or Pascal.

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

New Post(0)