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 advantages of Java reflection

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly explains "what are the advantages of Java reflection". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the advantages of Java reflection"?

Before talking about reflection, consider one question: how to create an object in java, and what are the ways?

There are probably several ways to create objects in Java:

1. Use the new keyword: this is our most common and simplest way to create objects

2. Use the Clone method: whenever we call an object's clone method, JVM will create a new object and copy all the contents of the previous object into it.

3. Use deserialization: when we serialize and deserialize an object, JVM creates a separate object for us

There are three common ways to create objects in Java. In fact, there is another way in addition to the above three, which is the "reflection" that we will discuss next.

1. Overview of reflection 1.1 what is reflection

In the running state of the program, all the properties and methods of this class (including private properties and methods) can be obtained for any class or object. This function of dynamically obtaining information and dynamically calling object methods is called reflection mechanism. To put it simply, through reflection, the class is completely transparent to us, and you can get anything you want.

Reflection maps parts of the Java class into Java objects that you can do after you get them. Since reflection is a component of a reflection Java class, we need to know what parts there are in a class?

For example, a class has: member variables, methods, constructors, and other information, using reflection technology we can map these components into objects.

1.2. What can reflexes do?

Generally speaking, reflection is used to make a framework, or you can do some low-level code with a high degree of abstraction. Reflection is not often used in daily development, but we must also understand it, because after understanding reflection, it can help us understand some of the principles of the framework. So there is a classic saying: reflection is the soul of frame design.

1.3 benefits of reflection

You can manipulate these objects while the program is running

It can be decoupled and the scalability of the program can be improved.

Before we learn about reflection, let's take a look at the three stages that Java code goes through in a computer:

Source source code phase: .java is compiled into a * .class bytecode file.

Class class object phase: the .class bytecode file is loaded into memory by the class loader and encapsulated into a Class object (used to describe the bytecode file in memory). The Class object extracts the member variables from the original bytecode file into an array Field [], extracts the constructor from the original bytecode file into an array Construction [], and encapsulates the member methods into an array Method []. Of course, there are not only these three in the Class class, but also a lot of packages, and these are the only three we commonly use.

RunTime runtime phase: the process of creating objects using new.

1.4There are three ways to get Class objects

[Source source code phase] Class.forName ("full class name"): loads the bytecode file into memory and returns the Class object

It is mostly used in the configuration file, defining the class name in the configuration file and loading the class by reading the configuration file.

[class class object phase] Class name .class: obtained through the attribute class of the class name

Mostly used for the transmission of parameters

[Runtime Runtime] object .getClass (): this method is a method defined in the Objec class, so all classes inherit this method.

Mostly used for objects to obtain bytecode

/ / method demonstration public class getClass {public static void main (String [] args) throws Exception {/ / method 1: Class.forName ("full class name"); Class class1 = Class.forName ("com.czxy.mybatis_plus.test.Person"); / / Person custom entity class System.out.println ("class1 =" + class1); / / method 2: class name .class Class class2 = Person.class System.out.println ("class2 =" + class2); / / method 3: object .getClass (); Person person = new Person (); Class class3 = person.getClass (); System.out.println ("class3 =" + class3); / / compare three objects System.out.println (class1 = = class2); / / true System.out.println (class1 = = class3) / / true}}

Running result:

From the above comparison of the results of the three objects, we can draw a conclusion: the same bytecode file (* .class) will only be loaded once during a program run, no matter which way the Class object is obtained.

2. The function 2.1of Class object to get the function

Only some commonly used ones are written here. Please refer to jdk's help documentation for details.

Get member variables

Field [] getFields () / / get all public-modified member variables Field getField (String name) / / get the specified name public-modified member variables Field [] getDeclaredFields () / / get all member variables, regardless of the modifier Field getDeclaredField (String name) / / get the specified member variables, regardless of the modifier

two。 Get the construction method

Constructor [] getConstructors () / / gets all the public-decorated constructor Constructor getConstructor (class. ParameterTypes) / / gets the specified public-modified constructor Constructor [] getDeclaredConstructors () / / gets all constructors, regardless of the modifier Constructor getDeclaredConstructor (class. ParameterTypes) / / gets the specified constructor, regardless of modifiers

3. Get member method

Method [] getMethods () / / gets all the public-modified member methods Method getMethod (String name, class. ParameterTypes) / / gets the public-modified member method Method [] getDeclaredMethods () / / of the specified name, regardless of the modifier Method getDeclaredMethod (String name, class. ParameterTypes) / / gets the member method with the specified name, regardless of modifiers

4. Get full class name

String getName () 2.2 Field: member variable

(1) set the value set (Object obj, Object value)

(2) get the value get (Object obj)

(3) ignore the security check of access modifier setAccessible (true): brute force reflex

2.3 tested entity class import lombok.Data;import lombok.ToString;@Data@ToStringpublic class Person {public String a; / / maximum range public protected String b; / / protected type String c; / / default access right private String d / / Private type} 2.4 Test getFields and getField (String name) methods / * get member variables * * Field [] getFields () * * Field getField (String name) * @ throws Exception * / public class reflectDemo {public static void main (String [] args) throws Exception {/ / get Person's Class object Class personClass = Person.class / / 1. Field [] getFields () gets all public modified member variables Field [] fields = personClass.getFields (); for (Field field: fields) {System.out.println (field);} System.out.println ("=") / / 2.Field getField (String name) gets the public-decorated member variable Field a = personClass.getField ("a") with the specified name; / / gets the value of the member variable a [only public, private or non-existent characters will throw an exception] Person p = new Person (); Object value = a.get (p) System.out.println ("value =" + value); / / because an is not assigned in the Person class, set the attribute value a.set (p, "Li Si") of the member variable a for null / /; System.out.println (p);}}

Running result:

2.5 Test getDeclaredFields and getDeclaredField (String name) methods / * * Field [] getDeclaredFields () * Field getDeclaredField (String name) * @ throws Exception * / public class reflectDemo1 {public static void main (String [] args) throws Exception {/ / get Person's Class object Class personClass = Person.class / / Field [] getDeclaredFields (): get all member variables, regardless of the modifier Field [] declaredFields = personClass.getDeclaredFields (); for (Field filed: declaredFields) {System.out.println (filed);} System.out.println ("=") / / Field getDeclaredField (String name) / / gets the specified member variable, regardless of the modifier Field d = personClass.getDeclaredField ("d"); / / private String d; Person p = new Person (); / / Object value1 = d.get (p) / / an exception will be thrown if it is obtained directly, because private variables can not be obtained directly by set and get, and the security check of the access modifier must be ignored before / / System.out.println ("value1 =" + value1); / / ignore the security check of the access modifier, also known as brute force reflection d.setAccessible (true) Object value2 = d.get (p); System.out.println ("value2 =" + value2);}}

Running result:

Note: if you do not ignore the access modifier, direct access will throw an exception like the following

3. Constructor: constructor 3.1 modifies the tested entity class import lombok.Data;import lombok.ToString;@Data@ToStringpublic class Person {private String name; private Integer age / / No parameter constructor public Person () {} / / single argument constructor, and private constructor private Person (String name) {} / / parameter constructor public Person (String name, Integer age) {this.name = name; this.age = age Test the method to get the constructor / * * get the constructor * Constructor [] getConstructors () * Constructor getConstructor (class. ParameterTypes) * / public class reflectDemo2 {public static void main (String [] args) throws Exception {/ / get the Class object of Person Class personClass = Person.class; / / Constructor [] getConstructors () / / get all the public-modified constructors Constructor [] constructors = personClass.getConstructors (); for (Constructor constructor: constructors) {System.out.println (constructor) } System.out.println ("= ="); / / get the no-parameter constructor Note: the Person class must have a non-parameter constructor, or throw an exception Constructor constructor1 = personClass.getConstructor (); System.out.println ("constructor1 =" + constructor1); / / use the obtained no-parameter constructor to create an object Object person1 = constructor1.newInstance () System.out.println ("person1 =" + person1); System.out.println ("= ="); / / get the parameter type of the constructor / / public Person (String name, Integer age) in the same order as within the constructor, and the parameter type is bytecode file type Constructor constructor2 = personClass.getConstructor (String.class,Integer.class); System.out.println ("constructor2 =" + constructor2) / / use the obtained parameter constructor to create the object Object person2 = constructor2.newInstance ("zhangsan", 22); / / if you get the parameter constructor, you must specify the parameter System.out.println (person2); System.out.println ("= =") / / for a general no-parameter constructor, instead of getting the no-parameter constructor first and initializing it, we directly call the newInstance () method Object person3 = personClass.newInstance () in the Class class; System.out.println ("person3 =" + person3);}}

Running result:

4. Method: method object 4.1 execution method: Object invoke (Object obj, Object... Args) import lombok.Data;import lombok.ToString;@Data@ToStringpublic class Person {private String name; private Integer age; / / No-parameter constructor public Person () {} / / Parametric constructor public Person (String name, Integer age) {this.name = name; this.age = age;} / / No-parameter method public void test () {System.out.println ("test...") } / / reload the parameter method public void test (String food) {System.out.println ("test..." + food);}} 4.2 Test the method to obtain the member method / * * Method [] getMethods () * * Method getMethod (String name, class. ParameterTypes) * / public class reflectDemo3 {public static void main (String [] args) throws Exception {/ / get the Class object of Person Class personClass = Person.class; / / the method to get the specified name Method method1 = personClass.getMethod ("test"); / / execute the method Person person = new Person (); Object rtValue = method1.invoke (person) / / if the method has a return type that can be obtained, null / / because the eat method does not return a value, output null System.out.println ("rtValue =" + rtValue); System.out.println ("- -") / / get the function with parameters, with two parameters: the first parameter is the method name, and the second parameter is the bytecode file Method method2 = personClass.getMethod ("test", String.class) that gets the parameter type of the method; / / executes the method method2.invoke (person, "hi"); System.out.println ("=") / / get the method list Method [] methods = personClass.getMethods (); for (Method method: methods) {/ / Note: the method obtained is not only its own method System.out.println (method) in the Person class; / / the method in the inheriting Object will also be obtained (provided, of course, it is modified by public)}

Running result:

We can see that all the public methods in Person are printed, and so are the public methods in Object.

As described earlier, methods with the Declared keyword can get methods with arbitrary modifiers. The setAccessible (true) method is also provided for violent reflex.

To sum up: there is no public and private ownership in front of the reflection, which can be solved through violent reflection.

5. Get the full class name 5.1 the class name obtained by the getName () method is the full class name (with path) public class getNameDemo {public static void main (String [] args) throws Exception {/ / get the Class object of Person Class personClass = Person.class;// get the full class name String className = personClass.getName (); System.out.println (className);}}

Running result:

6. application case of reflection mechanism 6.1 requirements

Write a "framework" that can help us create objects of any class and execute any methods without changing any code of the class.

6.2 implementation

(1) configuration file

(2) reflection mechanism

6.3 steps

(1) define the full class name of the object to be created and the method to be executed in the configuration file

(2) load the read configuration file in the program

(3) use reflection technology to load class files into memory.

(4) create an object

(5) execution method

6.4 entity classes required for code implementation

(1) Person class

Public class Person {/ / No-parameter method public void test () {System.out.println ("test...");}}

(2) Student class

Public class Student {/ / No-parameter method public void study () {System.out.println ("iTunm Student");} 6.5.Writing the configuration file className = com.czxy.mybatis_plus.test.PersonmethodName = test

6.6 implementation framework / * premise: no code of this class can be changed. You can create objects of any class and execute any method * that is: reject hard coding * / public class ReflectTest {public static void main (String [] args) throws Exception {/ / 1. Load configuration file / / 1.1 create Properties object Properties pro = new Properties (); / / 1.2 load configuration file / / 1.2.1 get the configuration file in the class directory (using classloader) ClassLoader classLoader = ReflectTest.class.getClassLoader (); InputStream inputStream = classLoader.getResourceAsStream ("pro.properties"); pro.load (inputStream); / / 2. Get the data defined in the configuration file String className = pro.getProperty ("className"); String methodName = pro.getProperty ("methodName"); / / 3. Load the class into memory Class cls = Class.forName (className); / / 4. Create the object Object obj = cls.newInstance (); / / 5. Get the method object Method method = cls.getMethod (methodName); / / 6. Execute method method.invoke (obj);}}

Running result:

6.7 modify the configuration file and run className = com.czxy.mybatis_plus.test.Student methodName = study again

Running result:

Thank you for your reading, the above is the content of "what are the advantages of Java reflection". After the study of this article, I believe you have a deeper understanding of the advantages of Java reflection, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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

Internet Technology

Wechat

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

12
Report