Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Java Reflection

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shares with you the content of the sample analysis of Java Reflection. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Reflection is one of the features of Java programming language, which allows running Java programs to check themselves, or "self-audit", and directly manipulate the internal properties of the program. For example, you can use it to get the names of each member of the Java class and display them.

This capability of Java may not be used much in practical applications, but it does not exist in other programming languages at all. For example, there is no way to get information about function definitions in a program in Pascal, C, or C++.

JavaBean is one of the practical applications of reflection, which allows some tools to visualize the operation of software components. These tools dynamically load and obtain the properties of Java components (classes) through reflection.

1. A simple example.

Consider the following simple example to see how 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 < m. Stories; iTunes +)

System.out.println (m [I] .toString ())

} catch (Throwable e) {

System.err.println (e)

}

}

}

Execute as follows:

Java DumpMethods java.util.Stack

Its output is as follows:

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)

This lists the party legal names of the java.util.Stack class as well as their qualifiers and return types.

This program uses Class.forName to load the specified class and then calls getDeclaredMethods to get the list of methods defined in the class. Java.lang.reflect.Methods is a class that describes a single method in a class.

two。 Start using Reflection

Classes for reflection, such as Method, can be found in the java.lang.relfect package. There are three steps to follow when using these classes: the first step is to get the java.lang.Class object of the class you want to operate on. In the running Java program, java.lang.Class class is used to describe classes and interfaces, etc.

Here is one of the ways to get a Class object:

Class c = Class.forName ("java.lang.String")

This statement gets a class object of the String class. There is another way, such as the following statement:

Class c = int.class

Or

Class c = Integer.TYPE

They can get class information of the basic type. The latter method accesses predefined TYPE fields in a basic type of wrapper class, such as Integer.

The second step is to call a method such as getDeclaredMethods to get a list of all the methods defined in the class.

Once you have this information, you can move on to the third step-- use reflection API to manipulate the information, such as the following 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 String as text.

In the following example, these three steps will provide examples for using reflection to deal with special applications.

Analog instanceof operator

After you get the class information, the next step is usually to solve some basic problems about Class objects. 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 []) {

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, you create a Class object of class A, and then check to see if some of the objects are instances of A. Integer (37) is not, but new A () is.

3. Find out the method of the class

Finding out what methods are defined in a class is a very valuable and basic reflection usage. The following code implements 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 methlist [] = cls.getDeclaredMethods ()

For (int I = 0; I < methlist.length; iTunes +) {

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 < pvec.length; jacks +)

System.out.println ("param #" + j + "" + pvec [j])

Class evec [] = m.getExceptionTypes ()

For (int j = 0; j < evec.length; jacks +)

System.out.println ("exc #" + j + "" + evec [j])

System.out.println ("return type =" + m.getReturnType ())

System.out.println ("-")

}

} catch (Throwable e) {

System.err.println (e)

}

}

}

This program first gets the description of the method1 class, and then calls getDeclaredMethods to get a series of Method objects that describe each method defined in the class, including public method, protected method, package method, private method, and so on. If you use getMethods instead of getDeclaredMethods in your program, you can also get information about inherited methods.

Once you have a list of Method objects, it is not difficult to display the parameter types, exception types, and return value types of these methods. Whether these types are basic types or class types can be given in order by the objects that describe the class.

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.NullPointerException

Return type = int

-

Name = main

Decl class = class method1

Param # 0 class [Ljava.lang.String

Return type = void

4. Get constructor information

The usage of the get class constructor is similar to that of 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 < ctorlist.length; iTunes +) {

Constructor ct = ctorlist [I]

System.out.println ("name =" + ct.getName ())

System.out.println ("decl class =" + ct.getDeclaringClass ())

Class pvec [] = ct.getParameterTypes ()

For (int j = 0; j < pvec.length; jacks +)

System.out.println ("param #" + j + "" + pvec [j])

Class evec [] = ct.getExceptionTypes ()

For (int j = 0; j < evec.length; jacks +)

System.out.println ("exc #" + j + "" + evec [j])

System.out.println ("-")

}

} catch (Throwable e) {

System.err.println (e)

}

}

}

The information about the return type was not obtained in this example because the constructor did not return the type.

The result of running this program is:

Name = constructor1

Decl class = class constructor1

-

Name = constructor1

Decl class = class constructor1

Param # 0 int

Param # 1 double

5. Get the field (domain) of the class

It is also possible to find out which data fields are defined in a class, and 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; iTunes +) {

Field fld = fieldlist [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 very similar to the previous one. A new thing, Modifier, is used in the example, which is also a reflection class that describes modifiers such as "private int" that describe field members. The modifiers themselves are described by integers and use Modifier.toString to return string descriptions in "official" 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 =

In the case of the get method, you can get only the field information declared in the current class (getDeclaredFields), or you can get the field defined in the parent class (getFields).

6. Execute the method according to the name of the method

At this point in the text, all the examples are related to how to get information about the class. We can also use reflection to do other things, such as executing a method with a specified name. The following example demonstrates this:

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)

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 only knows that a method needs to be executed somewhere, and the name of the method is specified during the run of the program (for example, this is done 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 named add with two integer parameters. Once the method is found and the corresponding Method object is created, execute it in the correct object instance. When you execute this method, you need to provide a list of parameters, which in the above example are two Integer objects wrapped with integers 37 and 47, respectively. The same Integer object is returned by executing the method, which encapsulates the return value of 84.

7. Create a new object

For constructors, you cannot execute a method, because executing a constructor means creating a new object (to be exact, the process of creating an object includes allocating memory and constructing the object). Therefore, the example most similar to 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 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)

}

}

}

Finds the appropriate constructor based on the specified parameter type and executes it to create a new object instance. It is valuable to use this method to create objects dynamically while the program is running, rather than at compile time.

8. Change the value of a field (field)

Another use of reflection is to change the value of the object data field. Reflection can find the field of an object by name from a running program and change it, as 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 value of field d is changed to 12.34.

9. Use array

The final use of the reflection introduced in this article is the created Operand array. An array is a special class type in the Java language, and a reference to an array can be assigned to an Object reference. Take a look at the following example to see how arrays work:

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)

}

}

}

In the example, you create a String array of 10 units, assign a value to the string in position 5, and finally get the string out of the array and print it out.

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 (cls)

Arrobj = Array.get (arrobj, 5)

Array.setInt (arrobj, 10, 37)

Int arrcast [] = (int []) arr

System.out.println (arrcast [3] [5] [10])

}

}

In the example, a 5 x 10 x 15 integer array is created and the element at [3] [5] [10] is assigned a value of 37. Note that a multidimensional array is actually an array of arrays. For example, after the first Array.get, arrobj is a 10 x 15 array. Then take one of the elements, an array of length 15, and use Array.setInt to assign a value to its 10th element.

Note that the type when creating the array is dynamic and is not known at compile time.

Thank you for reading! This is the end of this article on "sample Analysis of Java Reflection". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report