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

What are the classes in Java reflection

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

Share

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

In this article Xiaobian for you to introduce in detail "what are the classes in Java reflection", the content is detailed, the steps are clear, and the details are handled properly. I hope this article "what are the classes in Java reflection" can help you solve your doubts? let's follow the editor's ideas slowly to learn new knowledge.

1. What is reflection

The java.lang package provides the basic classes for programming in the java language. Under the lang package, there is a subpackage: reflect, where reflection-related APIs is located.

The official introduction to the reflect package is as follows:

Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.

The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class. It also allows programs to suppress default reflective access control.

Official introduction of java.lang.reflect

To put it simply, the reflection mechanism is like a class against a calm lake, which maps the fields, methods, constructors and other information of the class; the reflection mechanism can not only see the class information, but also make corresponding operations for fields, methods and so on.

Prepare for testing: creation of entity classes

For ease of explanation, first create an entity class to test the use of the

Package cn.byuan.entity;/** * student entity class * * @ author byuan * @ date 2022-01-25 * / public class Student {/ * student number, public variable, default value: defaultStudentNo * / public String studentNo = "defaultStudentNo"; / * * student name, public variable, default value: defaultStudentName * / public String studentName = "defaultStudentName" / * student gender, private variable, default value: defaultStudentSex * / private String studentSex = "defaultStudentSex"; / * * student age, private variable, default value: 0 * / private Integer studentAge = 0 / * / public Student () {} / * * Public full parameter construction method * / public Student (String studentNo, String studentName, String studentSex, Integer studentAge) {this.studentNo = studentNo; this.studentName = studentName; this.studentSex = studentSex; this.studentAge = studentAge } / * Private constructor * * / private Student (String studentSex, Integer studentAge) {this.studentSex = studentSex; this.studentAge = studentAge;} / * get/set method * * / public String getStudentNo () {return studentNo;} public Student setStudentNo (String studentNo) {this.studentNo = studentNo; return this } public String getStudentName () {return studentName;} public Student setStudentName (String studentName) {this.studentName = studentName; return this;} public String getStudentSex () {return studentSex;} public Student setStudentSex (String studentSex) {this.studentSex = studentSex; return this;} public Integer getStudentAge () {return studentAge } public Student setStudentAge (Integer studentAge) {this.studentAge = studentAge; return this } @ Override public String toString () {return "Student {" + "studentNo =" + this.studentNo + "," + "studentName =" + this.studentName + "," + "studentSex =" + this.studentSex + "," + "studentAge =" + this.studentAge + "}" } / * Student speaking methods * / private String speak (String message) {return this.studentName + ":" + message;}} 3. Several important categories and methods in reflex

Before learning about reflection, let's sort out what is contained in the next class (Class) itself.

Field, which is composed of modifier, field type, field name, corresponding value and so on.

Construction methods, construction methods can be simply divided into two categories: non-participation and parameters

A non-construction method, also known as a general method, is composed of modifiers, return value types, method names, formal parameter tables, method bodies, etc.

Several important categories of reflection discussed in this paper and their corresponding methods are based on the above.

(1) Class of important classes in reflection

The Class class represents the class itself, and the class itself contains fields, constructors, non-constructors, and so on, so the first step in using reflection is to get the Class class corresponding to the object.

Just in terms of using reflection, we need to focus on how to get the Class class. Here are some examples.

1. Class class test instance

Package cn.byuan.example;import cn.byuan.entity.Student;/** * several ways to obtain Class * * @ author byuan * @ date 2022-01-25 * / public class GetClassExample {public static void main (String [] args) throws ClassNotFoundException {/ / get class method 1: get the Class object Class getClassExample1 = Class.forName ("cn.byuan.entity.Student") through the full-path string of the class / / get class 2: get Class getClassExample2 = Student.class; / / get class directly through the class name 3: get the corresponding Class Student student1 = new Student () through the created object; Class getClassExample3 = student1.getClass ();}} (2) the Field of the important class in reflection

The Field class is the description of the properties in the class. With the cooperation of Class and Field, we can know what fields are in the class and deal with them accordingly.

1. The acquisition and common methods of Field class

The Class class provides us with two methods to get the Field class:

GetDeclaredFields (): get all declared fields (including public and private fields)

GetFields (): only public fields can be obtained

The Field class represents the property fields in the class, and the attribute fields in common classes can be divided into two categories: public fields (public) and private fields (private).

Each field has four attributes: modifier, field type, field name, and corresponding value. Field naturally provides corresponding methods to obtain these four attributes:

GetModifiers (): get the field modifier addition, which needs to be decoded by the toString method of the Modifier constant in order to obtain the explicit identity

GetType (): get the field type

GetName (): get the field name

Get (Object): get the corresponding value of the field

Examples are given below.

2. Field class test instance

Package cn.byuan.example;import cn.byuan.entity.Student;import java.lang.reflect.Field;import java.lang.reflect.Modifier;/** * several ways to get class fields * * @ author byuan * @ date 2021-01-25 * / public class GetFieldExample {public static void main (String [] args) throws IllegalAccessException {Class studentClass = Student.class / / two methods to get class fields: getDeclaredFields, getFields / / 1. GetDeclaredFields: get all declared fields (including public and private fields) Field [] declaredFieldArray = studentClass.getDeclaredFields (); printFieldInformation (declaredFieldArray); / / 2. GetFields: only public fields Field [] fieldArray = studentClass.getFields (); printFieldInformation (fieldArray) / / get the corresponding field value Student student = new Student () .setStudentSex ("female") .setStudentAge (18); printFieldValue (student) } / * * print class field information * * @ param fieldArray class field object list * * / public static void printFieldInformation (Field [] fieldArray) {for (Field fieldPart: fieldArray) {System.out.println ("print class field object:" + fieldPart) / / get field modifier String fieldModifier = Modifier.toString (fieldPart.getModifiers ()); / / get field type String fieldType = fieldPart.getType (). GetName (); / / get field name String fieldName = fieldPart.getName (); System.out.println (fieldModifier + "" + fieldType + "" + fieldName) } System.out.println ();} / * * print class field properties * * @ param t generic object * * / private static void printFieldValue (T) throws IllegalAccessException {Field [] fieldValueArray = t .getClass () .getDeclaredFields () For (Field fieldValuePart: fieldValueArray) {/ / cancel the language access check fieldValuePart.setAccessible (true) for possible private fields; / / Field name String filedName = fieldValuePart.getName (); / / Field corresponding value String fieldValue = fieldValuePart.get (t) .toString () System.out.println (filedName + "=" + fieldValue);}

Run screenshot

(3) Constructor of important classes in reflection

Constructor represents the constructor of a class, which is a class that manages all constructors

1. The acquisition and common methods of Constructor class

The Class class provides us with two methods to get the Constructor class:

GetDeclaredConstructors (): get all constructors

GetConstructors (): only public constructors can be obtained

Constructors can be simply divided into two categories: non-parametric constructors and parameterized constructors. Constructors are also a kind of methods, so any constructor is composed of modifiers, method names, formal parameter tables, and method bodies. Constructor naturally provides corresponding methods for its components:

Like fields, Constructors also provides the getModifiers () method: get the addition of the constructor modifier, and you need to decode it through the toString method of the Modifier constant to get the explicit identity.

GetName (): get the constructor name

GetParameterTypes (): gets the list of constructor parameters

Examples are given below.

2. Constructor class test instance

Several ways for package cn.byuan.example;import cn.byuan.entity.Student;import java.lang.reflect.Constructor;import java.lang.reflect.Modifier;/** * to obtain the construction method * * @ author byuan * @ date 2022-01-25 * / public class GetConstructorsExample {public static void main (String [] args) {Class studentClass = Student.class / / two methods to get the class constructor: getDeclaredConstructors, getConstructors / / 1. GetDeclaredConstructors: get all the constructors Constructor [] declaredConstructorArray = studentClass.getDeclaredConstructors (); printConstructorInformation (declaredConstructorArray); / / 2. GetConstructors, only the public constructor Constructor [] constructorArray = studentClass.getConstructors (); printConstructorInformation (constructorArray) } / * * print constructor information * * @ param constructorArray Constructor object list * * / public static void printConstructorInformation (Constructor [] constructorArray) {for (Constructor constructorPart: constructorArray) {System.out.println ("Direct print Constructor object:" + constructorPart) / / get constructor modifier String constructorModifier = Modifier.toString (constructorPart.getModifiers ()); / / get constructor name String constructorName = constructorPart.getName (); / / get constructor parameter list Class [] constructorParameterArray = constructorPart.getParameterTypes () / / print the constructor parameter list System.out.print (constructorModifier + "" + constructorName + "("); for (Class constructorParameterPart: constructorParameterArray) {System.out.print (constructorParameterPart.getName () + ");} System.out.println (") ");} System.out.println ();}}

Run screenshot

3. Instantiate objects using Constructor class

In general, we are not only concerned with getting specific information about the object constructor, but more importantly, how to instantiate objects using reflection. Constructor provides two types of methods for object instantiation:

GetConstructor (Class... ParameterTypes): gets the construction method of the specified parameter table, which can be used to obtain the construction method of no parameter / specified parameter

NewInstance (Object... Initargs): pass instantiated object parameters through a formal parameter table for use with getConstructor

Note: there is also a newInstance () method in Class, but it can only be used to call the class's parameterless constructor.

4. Constructor instantiates an object test example

The package cn.byuan.example;import cn.byuan.entity.Student;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;/** * constructor calls the instance * * @ author byuan * @ date 2022-01-26 * / public class ConstructorsInvokeExample {public static void main (String [] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {Class studentClass = Student.class; / / Class class newInstance method studentClass.newInstance (); / / 1. Call the public nonparametric constructor Object object1 = studentClass. GetConstructor (). NewInstance (); System.out.println (object1.getClass ()); / / 2. Call the public full parameter constructor Constructor studentConstructorFull = studentClass .getConstructor (String.class, Integer.class); Object object2 = studentConstructorFull .newInstance ("2022001", "Zhao Yi", "male", 18); System.out.println (object2); / / 3. Call private constructor Constructor studentConstructorPrivate = studentClass .getDeclaredConstructor (String.class, Integer.class); / / Private constructor needs to set accessible to true and cancel language access check studentConstructorPrivate.setAccessible (true); Object object3 = studentConstructorPrivate .newInstance ("female", 19); System.out.println (object3);}}

Run screenshot

(4) Method of important classes in reflection

The Method class describes the method information of the class

1. The acquisition and common methods of Method class

The Class class provides us with two methods to get the Method class:

GetDeclaredMethods (): get all non-constructor methods

GetMethods (): only public non-constructor methods are available

Any method can be divided into four parts: modifier, method name, formal parameter table, and method body. Method provides corresponding methods for its components:

GetModifiers (): gets the addition of method modifiers, which needs to be decoded by the toString method of the Modifier constant to get the explicit identity.

GetName (): get the method name

GetParameterTypes (): get the method parameter table

2. Method class test instance

Several ways for package cn.byuan.example;import cn.byuan.entity.Student;import java.lang.reflect.Method;import java.lang.reflect.Modifier;/** * to obtain non-construction methods * * @ author byuan * @ date 2022-01-26 * / public class GetMethodExample {public static void main (String [] args) {Class studentClass = Student.class / / get two methods of non-construction methods: getDeclaredMethods, getMethods / / 1. GetDeclaredMethods: get all non-construction methods Method [] declaredMethodArray = studentClass.getDeclaredMethods (); printMethodInformation (declaredMethodArray); / / 2. GetMethods, only public non-construction methods Method [] methodArray = studentClass.getMethods (); printMethodInformation (methodArray) } / * * print non-constructor method information * * @ param methodArray Constructor object list * * / public static void printMethodInformation (Method [] methodArray) {for (Method methodPart: methodArray) {System.out.println ("print non-constructor object directly:" + methodArray) / / get the non-constructor method modifier String methodModifier = Modifier.toString (methodPart.getModifiers ()); / / get the non-constructor method name String methodName = methodPart.getName (); String methodReturnType = methodPart.getReturnType (). GetName (); / / get the non-constructor method parameter list Class [] constructorParameterArray = methodPart.getParameterTypes () / / print non-constructor parameter list System.out.print (methodModifier + "" + methodReturnType + "" + methodName + "("); for (Class methodParameterPart: constructorParameterArray) {System.out.print (methodParameterPart.getName () + ");} System.out.println (") ");} System.out.println () }}

Run screenshot

3. Using Method to call non-construction methods

Similar to instantiating objects with Constructor, Method also needs two methods to call unconstructed methods

GetDeclaredMethod (method name, formal parameter array): gets all constructors

Invoke (object instance, parameter array): method call

4. Method calls a test example of a non-constructor

Package cn.byuan.example;import cn.byuan.entity.Student;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;/** * instance of non-constructor method call * * @ author byuan * @ date 2022-01-26 * / public class MethodInvokeExample {public static void main (String [] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {Class studentClass = Student.class / / for private non-constructor methods, you need to use getDeclaredMethod to get / / getDeclaredMethod (method name, formal parameter array) Method studentSpeakMethod = studentClass.getDeclaredMethod ("speak", new Class [] {String.class}); / / cancel language access check studentSpeakMethod.setAccessible (true) / / invoke (object instance, parameter array) Object object = studentSpeakMethod.invoke (studentClass.newInstance (), "Hello, world"); System.out.println (object);}}

Run screenshot

IV. Comprehensive practice: using reflection mechanism to write object copy tool class

In actual projects, we often encounter the situation that objects of POJO and VO are converted to each other. If we convert directly, we will use a lot of boilerplate code. In order to eliminate such code, we can write a simple object copy tool class to solve the problem.

(I) Business analysis

Obtain the Field array of the source object by reflection, and use the set/get method provided by the Field class to copy the attribute of the same name.

(2) entity class preparation

Create a Student class

Package cn.byuan.entity;/** * student entity class * * @ author byuan * @ date 2022-01-25 * / public class Student {/ * student number, public variable, default value: defaultStudentNo * / public String studentNo = "defaultStudentNo"; / * * student name, public variable, default value: defaultStudentName * / public String studentName = "defaultStudentName" / * student gender, private variable, default value: defaultStudentSex * / private String studentSex = "defaultStudentSex"; / * * student age, private variable, default value: 0 * / private Integer studentAge = 0 / * / public Student () {} / * * Public full parameter construction method * / public Student (String studentNo, String studentName, String studentSex, Integer studentAge) {this.studentNo = studentNo; this.studentName = studentName; this.studentSex = studentSex; this.studentAge = studentAge } / * Private constructor * * / private Student (String studentSex, Integer studentAge) {this.studentSex = studentSex; this.studentAge = studentAge;} public String getStudentNo () {return studentNo;} public Student setStudentNo (String studentNo) {this.studentNo = studentNo; return this;} public String getStudentName () {return studentName } public Student setStudentName (String studentName) {this.studentName = studentName; return this;} public String getStudentSex () {return studentSex;} public Student setStudentSex (String studentSex) {this.studentSex = studentSex; return this;} public Integer getStudentAge () {return studentAge;} public Student setStudentAge (Integer studentAge) {this.studentAge = studentAge; return this } @ Override public String toString () {return "Student {" + "studentNo =" + this.studentNo + "," + "studentName =" + this.studentName + "," + "studentSex =" + this.studentSex + "," + "studentAge =" + this.studentAge + "}" } / private String speak (String message) {return this.studentName + ":" + message;}}

Create a StudentOut class

Package cn.byuan.api.out;import cn.byuan.entity.Student;/** * student class reference * * @ author byuan * @ date 2022-01-26 * / public class StudentOut {/ * * student number, public variable * / private String studentNo; / * * student name, public variable * / private String studentName / * * student gender, private variable * / private String studentSex; / * * student age, private variable * * / private Integer studentAge; public String getStudentNo () {return studentNo;} public StudentOut setStudentNo (String studentNo) {this.studentNo = studentNo; return this;} public String getStudentName () {return studentName } public StudentOut setStudentName (String studentName) {this.studentName = studentName; return this;} public String getStudentSex () {return studentSex;} public StudentOut setStudentSex (String studentSex) {this.studentSex = studentSex; return this;} public Integer getStudentAge () {return studentAge;} public StudentOut setStudentAge (Integer studentAge) {this.studentAge = studentAge; return this } @ Override public String toString () {return "StudentOut {" + "studentNo =" + this.studentNo + "," + "studentName =" + this.studentName + "," + "studentSex =" + this.studentSex + "," + "studentAge =" + this.studentAge + "}";}} (III) tool class writing package cn.byuan.util Import cn.byuan.api.out.StudentOut;import cn.byuan.entity.Student;import java.lang.reflect.Field / * * object attribute copying tool class * * @ author byuan * @ date 2022-01-26 * / public class BeanUtil {/ * object copying tool * * @ param sourceObject source object * @ param destClass destination object corresponds to Class * * @ return after copying the object * * / public static T copyObject (Object sourceObject Class destClass) {if (sourceObject = = null) {return null } try {T destObject = destClass.newInstance (); copyField (sourceObject, destObject); return destObject;} catch (InstantiationException e) {e.printStackTrace ();} catch (IllegalAccessException e) {e.printStackTrace ();} catch (Exception e) {e.printStackTrace () } return null;} / * object attribute copying tool * * @ param sourceObject Source object * @ param destObject destination object * * / private static void copyField (Object sourceObject, Object destObject) {if (sourceObject = = null | | destObject = = null) {return } / / get all the fields of the source object Field [] sourceFieldArray = sourceObject.getClass () .getDeclaredFields (); for (Field sourceFieldPart: sourceFieldArray) {/ / cancel language access check sourceFieldPart.setAccessible (true); String sourceFieldName = sourceFieldPart.getName () Try {/ / get the corresponding class field Field destField = destObject .getClass () .getDeclaredField (sourceFieldName); destField.setAccessible (true); destField.set (destObject, sourceFieldPart.get (sourceObject)) of the target object based on the attribute name } catch (NoSuchFieldException e) {e.printStackTrace ();} catch (IllegalAccessException e) {e.printStackTrace ();} public static void main (String [] args) {Student student = new Student ("2022001", "Zhao Yi", "male", 18); StudentOut studentOut = copyObject (student, StudentOut.class) System.out.println (studentOut);}}

Run screenshot

After reading this, the article "what are the classes in Java reflection" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, you are welcome to follow the industry information channel.

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