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

How to parse Java reflection

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I will talk to you about how to analyze Java reflection. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

1. What is reflection

Reflection is to map the components of the Java class into Java objects one by one. That is, in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties. This function of dynamically obtaining information and dynamically calling object methods is called Java reflection mechanism.

1. The function of the reflection mechanism

The Java reflection mechanism mainly provides the following functions:

Determines 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 that any class has at run time.

Call the method of any object at run time.

Generate a dynamic proxy.

two。 Classes that implement the reflection mechanism

The Java reflection mechanism is mainly implemented by the following classes in Java (all of which are in the java.lang.reflect package):

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.

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

Second, the use of reflection

Here's a step-by-step explanation of how to get what we need through reflection.

Let's write a random Customer class (that is, a PO class), and then see how to manipulate this class through reflection.

1. The Customer class previously wrote about the proxy pattern of the design pattern, because the next dynamic proxy needs to use the knowledge of reflection, so write another article about reflection on the basis of the previous Java article, or based on the actual program, to understand what reflection is and how it should be used. First, what is reflection is to map the components of the Java class into Java objects one by one. That is, in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties. This function of dynamically obtaining information and dynamically calling object methods is called Java reflection mechanism. 1. The function of the reflection mechanism the Java reflection mechanism mainly provides the following functions: to determine the class to which any object belongs at runtime. Construct an object of any class at run time. Determine the member variables and methods that any class has at run time. Call the method of any object at run time. Generate a dynamic proxy. two。 The Java class that implements the reflection mechanism is mainly implemented by the following classes (all in the java.lang.reflect package): the 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. Array class: provides static methods for creating arrays dynamically and accessing the elements of the array. Second, the use of reflection the following step-by-step instructions on how to get what we need through reflection. Let's write a random Customer class (that is, a PO class), and then see how to manipulate this class through reflection. 1. Customer class 1 public class Customer {2 3 private Long id; 4 private String name; 5 private int age; 6 7 public Customer () {} 8 9 public Customer (String name,int age) {10 this.name = name;11 this.age = age;12} 13 14 public Long getId () {15 return id 16} 17 public void setId (Long id) {18 this.id=id;19} 20 public String getName () {21 return name;22} 23 public void setName (String name) {24 this.name=name;25} 26 public int getAge () {27 return age;28} 29 public void setAge (int age) {30 this.age=age 31} 32 33} 2. The ReflectTester class is used to demonstrate the basic usage of Reflection API. The custom copy method is used to create an object of the same type as the parameter objcet, and then copy all the properties in the object object into the newly created object and return it. 1 import java.lang.reflect.Field; 2 import java.lang.reflect.Method; 3 4 public class ReflectTester {56 public Object copy (Object object) throws Exception {7 / / get the type of object 8 Class classType=object.getClass (); 9 System.out.println ("Class:" + classType.getName ()) 10 11 / / create a new object 12 Object objectCopy=classType.getConstructor (new Class [] {}) .newInstance (new Object [] {}) by default constructor; 13 14 / get all the attributes of the object 15 Field fields [] = classType.getDeclaredFields (); 16 17 for (int item0; I clazz = Class.forName (className); 50 Field [] fields = clazz.getDeclaredFields () 51 for (Field field: fields) {52 sBuffer.append ("attribute name\ t:" + field.getName () + "\ n"); 53 System.out.println ("attribute name\ t:" + field.getName ()) 54 sBuffer.append ("- attribute type\ t:" + field.getType () + "\ n"); 55 System.out.println ("- attribute type\ t:" + field.getType ()) 56} 57 58 / / get the method name 59 Method [] methods = myClass.getMethods () 60 for (Method method: methods) {61 if (method.toString (). IndexOf (className) > 0) {62 sBuffer.append ("method name\ t:" + method.toString () .substring (method.toString (). IndexOf (className)) + "\ n")) 63 System.out.println ("method name\ t:" + method.toString () .substring (method.toString () .indexOf (className) 64} 65} 66 sBuffer.append -"+"\ n ") 67 System.out.println ("-) 68} 69} 70} 71} catch (Exception e) {72 e.printStackTrace (); 73} finally {74 sBuffer.append ("End"); 75 System.out.println ("End"); 76 77 WriteFile.write (sBuffer) / / write file 78} 79} 80 81} 2. WriteFile class to write file operation. 1 import java.io.BufferedWriter; 2 import java.io.File; 3 import java.io.FileWriter; 4 5 / * * 6 * @ ClassName: WriteFile 7 * @ Description: write file operation 8 * @ author adamjwh 9 * @ date May 28, 2018 10 * 11 * / 12 public class WriteFile {13 14 private static String pathname = "src/com/adamjwh/jnp/ex14/out.txt" 15 16 public static void write (StringBuffer sBuffer) throws Exception {17 File file = new File (pathname); 18 BufferedWriter bw = new BufferedWriter (new FileWriter (file)); 19 20 bw.write (sBuffer.toString ()); 21 bw.close () 22} 23 24} 3. Main class here we need to create a new lib folder under the project, and then put the parsed jar package into it, for example, here we put the dt.jar of jdk. The directory structure is as follows: executive program: 1 / * * 2 * @ ClassName: Main 3 * @ Description: 4 * @ author adamjwh 5 * @ date May 28, 2018 6 * 7 * / 8 public class Main {9 10 private static String jar = "lib/dt.jar"; 11 12 public static void main (String [] args) throws Exception {13 ReflexDemo.getJar (jar) 14} 1516} the running result is as follows: 2. ReflectTester class

This class is used to demonstrate the basic usage of Reflection API. The custom copy method is used to create an object of the same type as the parameter objcet, and then copy all the properties in the object object into the newly created object and return it.

I wrote about the proxy pattern of the design pattern before, because the next dynamic proxy needs to use the knowledge of reflection, so on the basis of the previous Java article, I wrote another article about reflection, mainly based on the actual program, to understand what reflection is and how it should be used. First, what is reflection is to map the components of the Java class into Java objects one by one. That is, in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties. This function of dynamically obtaining information and dynamically calling object methods is called Java reflection mechanism. 1. The function of the reflection mechanism the Java reflection mechanism mainly provides the following functions: to determine the class to which any object belongs at runtime. Construct an object of any class at run time. Determine the member variables and methods that any class has at run time. Call the method of any object at run time. Generate a dynamic proxy. two。 The Java class that implements the reflection mechanism is mainly implemented by the following classes (all in the java.lang.reflect package): the 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. Array class: provides static methods for creating arrays dynamically and accessing the elements of the array. Second, the use of reflection the following step-by-step instructions on how to get what we need through reflection. Let's write a random Customer class (that is, a PO class), and then see how to manipulate this class through reflection. 1. Customer class 1 public class Customer {2 3 private Long id; 4 private String name; 5 private int age; 6 7 public Customer () {} 8 9 public Customer (String name,int age) {10 this.name = name;11 this.age = age;12} 13 14 public Long getId () {15 return id 16} 17 public void setId (Long id) {18 this.id=id;19} 20 public String getName () {21 return name;22} 23 public void setName (String name) {24 this.name=name;25} 26 public int getAge () {27 return age;28} 29 public void setAge (int age) {30 this.age=age 31} 32 33} 2. The ReflectTester class is used to demonstrate the basic usage of Reflection API. The custom copy method is used to create an object of the same type as the parameter objcet, and then copy all the properties in the object object into the newly created object and return it. 1 import java.lang.reflect.Field; 2 import java.lang.reflect.Method; 3 4 public class ReflectTester {56 public Object copy (Object object) throws Exception {7 / / get the type of object 8 Class classType=object.getClass (); 9 System.out.println ("Class:" + classType.getName ()) 10 11 / / create a new object 12 Object objectCopy=classType.getConstructor (new Class [] {}) .newInstance (new Object [] {}) by default constructor; 13 14 / get all the attributes of the object 15 Field fields [] = classType.getDeclaredFields (); 16 17 for (int item0; I clazz = Class.forName (className); 50 Field [] fields = clazz.getDeclaredFields () 51 for (Field field: fields) {52 sBuffer.append ("attribute name\ t:" + field.getName () + "\ n"); 53 System.out.println ("attribute name\ t:" + field.getName ()) 54 sBuffer.append ("- attribute type\ t:" + field.getType () + "\ n"); 55 System.out.println ("- attribute type\ t:" + field.getType ()) 56} 57 58 / / get the method name 59 Method [] methods = myClass.getMethods () 60 for (Method method: methods) {61 if (method.toString (). IndexOf (className) > 0) {62 sBuffer.append ("method name\ t:" + method.toString () .substring (method.toString (). IndexOf (className)) + "\ n")) 63 System.out.println ("method name\ t:" + method.toString () .substring (method.toString () .indexOf (className) 64} 65} 66 sBuffer.append -"+"\ n ") 67 System.out.println ("-) 68} 69} 70} 71} catch (Exception e) {72 e.printStackTrace (); 73} finally {74 sBuffer.append ("End"); 75 System.out.println ("End"); 76 77 WriteFile.write (sBuffer) / / write file 78} 79} 80 81} 2. WriteFile class to write file operation. 1 import java.io.BufferedWriter; 2 import java.io.File; 3 import java.io.FileWriter; 4 5 / * * 6 * @ ClassName: WriteFile 7 * @ Description: write file operation 8 * @ author adamjwh 9 * @ date May 28, 2018 10 * 11 * / 12 public class WriteFile {13 14 private static String pathname = "src/com/adamjwh/jnp/ex14/out.txt" 15 16 public static void write (StringBuffer sBuffer) throws Exception {17 File file = new File (pathname); 18 BufferedWriter bw = new BufferedWriter (new FileWriter (file)); 19 20 bw.write (sBuffer.toString ()); 21 bw.close () 22} 23 24} 3. Main class here we need to create a new lib folder under the project, and then put the parsed jar package into it, for example, here we put the dt.jar of jdk. The directory structure is as follows: executive program: 1 / * * 2 * @ ClassName: Main 3 * @ Description: 4 * @ author adamjwh 5 * @ date May 28, 2018 6 * 7 * / 8 public class Main {9 10 private static String jar = "lib/dt.jar"; 11 12 public static void main (String [] args) throws Exception {13 ReflexDemo.getJar (jar) 14} 15 16} the running result is as follows:

Let's analyze the above code.

First, get the type of the object through the getClass () method in the Object class.

Class classType=object.getClass ()

The Class class is the core class in Reflection API. The main methods are as follows:

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 the specific method of the class, the name parameter 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.

NewInstance (): creates an object of the class through the constructor of the class without arguments.

The second step is to create a new object through the default constructor, that is, first call the getConstructor () method of the Class class to get a Constructor object, which represents the default constructor, and then call the newInstance () method of the Constructor object to construct an instance.

Object objectCopy=classType.getConstructor (new Class [] {}) .newInstance (new Object [] {})

The third step is to get all the properties of the object, that is, to return all the properties of the class through the getDeclaredFields () method of the Class class, including the properties of the public, protected, default and private access levels

Field fields [] = classType.getDeclaredFields ()

The fourth step is to get the corresponding get/set methods for each property, and then execute these methods to copy the original object properties into the new object.

Here we can write a class of InvokeTester, and then use the reflection mechanism to call the add () method of an InvokeTester object (custom method). For example, if the two parameters of the add () method are of type int, 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 invoke method of Method is also used in the above code, whose receiving parameter must be an object, and if the parameter is a basic data type, it must be converted to an object of the corresponding wrapper type, such as int to be converted to Integer. The return value of the invoke method is always the object, and if the return type of the actual called method is the basic data type, then the invoke method converts it to an object of the corresponding wrapper type and returns it.

The following is a simple test. Specific method calls, such as the add method mentioned above, can be written by yourself (see the following section for specific examples):

Public static void main (String [] args) throws Exception {Customer customer = new Customer (); customer.setId (10L); customer.setName ("adam"); customer.setAge (3); new ReflectTester () .copy (customer);}

The running results are as follows:

III. Specific examples

Next we try to analyze the class in a jar package through the reflection mechanism, extract all the properties and methods in the class and write them into a file.

The directory structure is as follows:

1. ReflexDemo class

The main part of the code, through reflection to obtain classes, properties and methods.

Import java.io.File;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.net.URL;import java.net.URLClassLoader;import java.util.Enumeration;import java.util.jar.JarEntry;import java.util.jar.JarFile;/** * @ ClassName: ReflexDemo * @ Description: obtain classes, properties and methods through reflection * @ author adamjwh * @ date May 28, 2018 * * / public class ReflexDemo {private static StringBuffer sBuffer Public static void getJar (String jar) throws Exception {try {File file = new File (jar); URL url = file.toURI (). ToURL (); URLClassLoader classLoader = new URLClassLoader (new URL [] {url}, Thread.currentThread (). GetContextClassLoader ()); JarFile jarFile = new JarFile (jar); Enumeration enumeration = jarFile.entries () JarEntry jarEntry; sBuffer = new StringBuffer (); / / data while (enumeration.hasMoreElements ()) {jarEntry = enumeration.nextElement (); if (jarEntry.getName (). IndexOf ("META-INF")

< 0) { String classFullName = jarEntry.getName(); if (classFullName.indexOf(".class") < 0) { classFullName = classFullName.substring(0, classFullName.length() - 1); } else { // 去除后缀.class,获得类名 String className = classFullName.substring(0, classFullName.length() - 6).replace("/", "."); Class myClass = classLoader.loadClass(className); sBuffer.append("类名\t:" + className); System.out.println("类名\t:" + className); // 获得属性名 Class clazz = Class.forName(className); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { sBuffer.append("属性名\t:" + field.getName() + "\n"); System.out.println("属性名\t:" + field.getName()); sBuffer.append("-属性类型\t:" + field.getType() + "\n"); System.out.println("-属性类型\t:" + field.getType()); } // 获得方法名 Method[] methods = myClass.getMethods(); for (Method method : methods) { if (method.toString().indexOf(className) >

0) {sBuffer.append ("method name\ t:" + method.toString (). Substring (method.toString (). IndexOf (className)) + "\ n"); System.out.println ("method name\ t:" + method.toString (). Substring (method.toString (). IndexOf (className) }} sBuffer.append ("- -"+"\ n ") System.out.println ("-") } catch (Exception e) {e.printStackTrace ();} finally {sBuffer.append ("End"); System.out.println ("End"); WriteFile.write (sBuffer); / / write file}} 2. WriteFile class

Perform a file write operation.

Import java.io.File;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.net.URL;import java.net.URLClassLoader;import java.util.Enumeration;import java.util.jar.JarEntry;import java.util.jar.JarFile;/** * @ ClassName: ReflexDemo * @ Description: obtain classes, properties and methods through reflection * @ author adamjwh * @ date May 28, 2018 * * / public class ReflexDemo {private static StringBuffer sBuffer Public static void getJar (String jar) throws Exception {try {File file = new File (jar); URL url = file.toURI (). ToURL (); URLClassLoader classLoader = new URLClassLoader (new URL [] {url}, Thread.currentThread (). GetContextClassLoader ()); JarFile jarFile = new JarFile (jar); Enumeration enumeration = jarFile.entries () JarEntry jarEntry; sBuffer = new StringBuffer (); / / data while (enumeration.hasMoreElements ()) {jarEntry = enumeration.nextElement (); if (jarEntry.getName (). IndexOf ("META-INF")

< 0) { String classFullName = jarEntry.getName(); if (classFullName.indexOf(".class") < 0) { classFullName = classFullName.substring(0, classFullName.length() - 1); } else { // 去除后缀.class,获得类名 String className = classFullName.substring(0, classFullName.length() - 6).replace("/", "."); Class myClass = classLoader.loadClass(className); sBuffer.append("类名\t:" + className); System.out.println("类名\t:" + className); // 获得属性名 Class clazz = Class.forName(className); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { sBuffer.append("属性名\t:" + field.getName() + "\n"); System.out.println("属性名\t:" + field.getName()); sBuffer.append("-属性类型\t:" + field.getType() + "\n"); System.out.println("-属性类型\t:" + field.getType()); } // 获得方法名 Method[] methods = myClass.getMethods(); for (Method method : methods) { if (method.toString().indexOf(className) >

0) {sBuffer.append ("method name\ t:" + method.toString (). Substring (method.toString (). IndexOf (className)) + "\ n"); System.out.println ("method name\ t:" + method.toString (). Substring (method.toString (). IndexOf (className) }} sBuffer.append ("- -"+"\ n ") System.out.println ("-") } catch (Exception e) {e.printStackTrace ();} finally {sBuffer.append ("End"); System.out.println ("End"); WriteFile.write (sBuffer); / / write file} 3. Main class

Here we need to create a new lib folder under the project, and then put the parsed jar package into it, for example, here we put the dt.jar of jdk. The directory structure is as follows:

Execute the program:

Import java.io.File;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.net.URL;import java.net.URLClassLoader;import java.util.Enumeration;import java.util.jar.JarEntry;import java.util.jar.JarFile;/** * @ ClassName: ReflexDemo * @ Description: obtain classes, properties and methods through reflection * @ author adamjwh * @ date May 28, 2018 * * / public class ReflexDemo {private static StringBuffer sBuffer Public static void getJar (String jar) throws Exception {try {File file = new File (jar); URL url = file.toURI (). ToURL (); URLClassLoader classLoader = new URLClassLoader (new URL [] {url}, Thread.currentThread (). GetContextClassLoader ()); JarFile jarFile = new JarFile (jar); Enumeration enumeration = jarFile.entries () JarEntry jarEntry; sBuffer = new StringBuffer (); / / data while (enumeration.hasMoreElements ()) {jarEntry = enumeration.nextElement (); if (jarEntry.getName (). IndexOf ("META-INF")

< 0) { String classFullName = jarEntry.getName(); if (classFullName.indexOf(".class") < 0) { classFullName = classFullName.substring(0, classFullName.length() - 1); } else { // 去除后缀.class,获得类名 String className = classFullName.substring(0, classFullName.length() - 6).replace("/", "."); Class myClass = classLoader.loadClass(className); sBuffer.append("类名\t:" + className); System.out.println("类名\t:" + className); // 获得属性名 Class clazz = Class.forName(className); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { sBuffer.append("属性名\t:" + field.getName() + "\n"); System.out.println("属性名\t:" + field.getName()); sBuffer.append("-属性类型\t:" + field.getType() + "\n"); System.out.println("-属性类型\t:" + field.getType()); } // 获得方法名 Method[] methods = myClass.getMethods(); for (Method method : methods) { if (method.toString().indexOf(className) >

0) {sBuffer.append ("method name\ t:" + method.toString (). Substring (method.toString (). IndexOf (className)) + "\ n"); System.out.println ("method name\ t:" + method.toString (). Substring (method.toString (). IndexOf (className) }} sBuffer.append ("- -"+"\ n ") System.out.println ("-") } catch (Exception e) {e.printStackTrace ();} finally {sBuffer.append ("End"); System.out.println ("End"); WriteFile.write (sBuffer); / / write file}

The running results are as follows:

After reading the above, do you have any further understanding of how to parse Java reflection? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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