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

Case Analysis of Java reflection Mechanism

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail the case analysis of Java reflection mechanism, the content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

In the Java runtime environment, is it possible to know what properties and methods there are for any class? For any

Can an object call any of its methods? The answer is yes. This dynamic acquisition of class information, as well as dynamics

The function of calling the method of an object comes from the Reflection mechanism of the Java language. The Java reflection mechanism mainly provides

The following features are available:

Determine the class to which any object belongs at run time

Construct an object of any class at run time

Determine the member variables and methods of any class at run time

Call the method of any object at run time

Generate a dynamic proxy.

In JDK, the Java reflection mechanism is mainly implemented by the following classes, all of which are located in java.lang.reflect

In the bag.

Class class: represents a class.

Field class: represents the member variable of the class (member variable is also called the property of the class).

Method class: a method that represents a class.

Constructor class: represents the constructor of the class.

The Array class: provides static methods for dynamically creating arrays and accessing array elements.

The DumpMethods class, shown in routine 1, demonstrates the basic role of Reflection API, which reads commands

The name of the class specified by the line parameter, and then print the method information that the class has:

Routine 1:DumpMethods.java

Java code

Import java.lang.reflect.*; public class DumpMethods {public static void main (String args []) throws Exception {/ / load and initialize the class Class classType = Class.forName (args [0]) specified by the command line parameter; / / get all the methods of the class Method methods [] = classType.getDeclaredMethods (); for (int I = 0; I < methods.length) I added) System.out.println (methods [I] .toString ());}}

Running the command "java DumpMethods java.util.Stack" displays the methods that the java.util.Stack class has, and the program prints as follows:

Public synchronized java.lang.Object java.util.Stack.pop () public java.lang.Object java.util.Stack.push (java.lang.Object) public boolean java.util.Stack.empty () public synchronized java.lang.Object java.util.Stack.peek () public synchronized int java.util.Stack.search (java.lang.Object)

The ReflectTester class shown in routine 2 further demonstrates the basic use of Reflection API.

The ReflectTester class has a copy (Object object) method that creates an object of the same type as the parameter object, then copies all the properties in the object object to the newly created object and returns it. This example can only copy a simple JavaBean, assuming that each property of JavaBean has a public type

The getXXX () and setXXX () methods.

Routine 2 ReflectTester.java

Java code

Import java.lang.reflect.*; public class ReflectTester {public Object copy (Object object) throws Exception {/ / get the type of object Class classType = object.getClass (); System.out.println ("Class:" + classType.getName ()) / / create a new object Object objectCopy = classType.getConstructor (new Class [] {}) .newInstance (new Object [] {}) by default constructor; / / get all properties of the object Field fields [] = classType.getDeclaredFields (); for (int I = 0; I < fields.length) Field field +) {Field field = fields [I]; String fieldName = field.getName (); String firstLetter = fieldName.substring (0,1). ToUpperCase (); / / get the name of the getXXX () method corresponding to the attribute String getMethodName = "get" + firstLetter + fieldName.substring (1) / / get the name of the setXXX () method corresponding to the attribute String setMethodName = "set" + firstLetter + fieldName.substring (1); / / get the getXXX () method Method getMethod = classType.getMethod (getMethodName, new Class [] {}) corresponding to the attribute / / get the setXXX () method Method setMethod = classType.getMethod (setMethodName, new Class [] {field.getType ()}) corresponding to the attribute; / / call the getXXX () method Object value = getMethod.invoke (object, new Object [] {}) of the original object. System.out.println (fieldName + ":" + value); / / call the setXXX () method setMethod.invoke (objectCopy, new Object [] {value}) of the copied object;} return objectCopy;} public static void main (String [] args) throws Exception {Customer customer = new Customer ("Tom", 21) Customer.setId (new Long (1)); Customer customerCopy = (Customer) new ReflectTester (). Copy (customer); System.out.println ("Copy information:" + customerCopy.getName () + "" + customerCopy.getAge ());}} class Customer {/ / Customer class is a JavaBean private Long id; private String name Private int age; public Customer () {} public Customer (String name, int age) {this.name = name; this.age = age;} public Long getId () {return id;} public void setId (Long id) {this.id = id } public String getName () {return name;} public void setName (String name) {this.name = name;} public int getAge () {return age;} public void setAge (int age) {this.age = age;}}

Execution result: Class:Customer

Id:1

Name:Tom

Age:21

Copy information:Tom 21

The Class class is the core class in Reflection API and has the following methods.

GetName (): gets the full name of the class.

GetFields (): gets the property of the public type of the class.

GetDeclaredFields (): gets all the properties of the class.

GetMethods (): the method to get the public type of the class.

GetDeclaredMethods (): gets all the methods of the class.

GetMethod (String name, Class [] parameterTypes): get a specific method of the class, name parameter

The number specifies the name of the method, and the parameterTypes parameter specifies the parameter type of the method.

GetConstrutors (): gets the constructor of the public type of the class.

GetConstrutor (Class [] parameterTypes): gets the specific constructor of the class, and the parameterTypes parameter specifies the parameter type of the constructor.

In the main () method of the InvokeTester class, as shown in routine 3, the reflection mechanism is used to call a

The add () and echo () methods of the InvokeTester object.

Routine 3 InvokeTester.java

Java code

Import java.lang.reflect.*; public class InvokeTester {public int add (int param1, int param2) {return param1 + param2;} public String echo (String msg) {return "echo:" + msg;} public static void main (String [] args) throws Exception {Class classType = InvokeTester.class; Object invokeTester = classType.newInstance () / call the add () method of the InvokeTester object Method addMethod = classType.getMethod ("add", new Class [] {int.class, int.class}); Object result = addMethod.invoke (invokeTester, new Object [] {new Integer, new Integer); System.out.println ((Integer) result) / call the echo () method of the InvokeTester object Method echoMethod = classType.getMethod ("echo", new Class [] {String.class}); result = echoMethod.invoke (invokeTester, new Object [] {"Hello"}); System.out.println ((String) result);}}

Implementation result: 300

Echo:Hello

The two parameters of the add () method are of type int, and the code to get the Method object that represents the add () method is as follows:

Method addMethod=classType.getMethod ("add", new Class [] {int.class,int.class})

The parameters received by the invoke (Object obj,Object args []) method of the Method class must be objects, and if the parameters are primitive type data, they must be converted to objects of the corresponding wrapper type. The return value of the invoke () method is always the object

If the return type of the actual called method is primitive type data, then the invoke () method converts it to a phase

The object of the type that should be wrapped, and then return it.

In this example, although the two parameters and return values of the add () method of the InvokeTester class are of type int, call the

When you use the invoke () method of the addMethod object, you can only pass parameters of type Integer, and the return type of the invoke () method is also of type Integer, and the Integer class is a wrapper class for the basic type of int:

Object result=addMethod.invoke (invokeTester

New Object [] {new Integer (100,200)})

System.out.println ((Integer) result); / / result is Integer type

The java.lang.Array class provides various static methods for dynamically creating and accessing array elements. Such as routine 10-4

The main () method of the ArrayTester1 class shown creates an array of strings of length 10, and then indexes the

The element at position 5 is set to "hello", and then the value of the element at index position 5 is read.

Routine 10-4 ArrayTester1.java

Java code

Import java.lang.reflect.*; public class ArrayTester1 {public static void main (String args []) throws Exception {Class classType = Class.forName ("java.lang.String"); / / create a string array of length 10 Object array = Array.newInstance (classType, 10) / / set the element with index position 5 to "hello" Array.set (array, 5, "hello"); / / read the value of the element with index position 5 String s = (String) Array.get (array, 5); System.out.println (s); / / output hello}}

The main () method of the ArrayTester2 class as shown in routine 10-5 creates a 5 × 10 × 15 integer.

Group and set the value of the element whose index position is [3] [5] [10] to set 37.

Java code

Import java.lang.reflect.*; public class ArrayTester2 {public static void main (String args []) {int dims [] = new int [] {5,10,15}; Object array = Array.newInstance (Integer.TYPE, dims); / / make arrayObj reference array [3] Object arrayObj = Array.get (array, 3); Class cls = arrayObj.getClass (). GetComponentType () System.out.println (cls); / / make arrayObj reference array [3] [5] arrayObj = Array.get (arrayObj, 5); / / set element array [3] [5] [10] to 37 Array.setInt (arrayObj, 10,37); int arrayCast [] = (int []) array System.out.println (arrayCast [3] [5] [10]);}}

Output:

Class [I

37???

This is the end of the case analysis of Java reflection mechanism. I hope the above content can be helpful to you and 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