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 Code Analysis of reflection Mechanism in Java Development

2025-04-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

In this article Xiaobian for you to introduce in detail "Java development reflection mechanism example code analysis", the content is detailed, the steps are clear, the details are handled properly, I hope this "Java development reflection mechanism example code analysis" article can help you solve your doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.

Preface

There is such a class:

Package com.example.demo;import com.alibaba.fastjson.annotation.JSONField;public class User {private String name; @ Value (value = "age_a") private String age; public String getName () {return name;} public void setName (String name) {this.name = name;} public String getAge () {return age;} public void setAge (String age) {this.age = age 1. Three ways to create Class

1-Class clazz = Class.forName ("com.example.demo.User")

Note that the class name of forName ("xxx") here needs to be a full name, and it is an interface or class, otherwise it cannot be loaded.

2-User user = new User ()

Class clazz2 = user.getClass ()

3-Class clazz3 = User.class

In all of the above three ways, you can get the Class object like User, and through Class, you can start playing with reflection.

Reflection gets all the attributes and attribute types of the class

Class clazz = User.class;Field [] fields = clazz.getDeclaredFields (); for (Field field: fields) {System.out.println ("attribute name:" + field.getName ()); System.out.println ("Type of attribute:" + field.getGenericType (). GetTypeName ());}

Properties and attribute types of printout User--

Attribute name: name

Type of attribute: java.lang.String

Attribute name: age

Type of attribute: java.lang.String

After you use reflection to get the field properties of a class, can you use reflection to create an object? The answer is yes.

For example, you can create an object by reflecting the field properties similar to the following code.

Map fileds = new HashMap (); fileds.put ("name", "Zhang San"); fileds.put ("age", "10"); Object o = User.class.newInstance (); Field [] fields = o.getClass (). GetDeclaredFields (); for (Field field: fields) {/ / after setting, you can access the private variable field.setAccessible (true) with reflection / / assign a value to the attribute by reflection field.set (field.getName fileds.get (field.getName ();} User user1 = (User) o; System.out.println (user1.toString ())

In what scenarios might you need to do this? Like the mapping of some internal data and external data fields, we can map the source data to the target data through similar field reflection, and then get the target objects that can be inserted into the database.

Third, reflection dynamically modifies the annotation value of class attributes

Note that when we set up the User class, we annotated one of the fields: @ Value (value = "age_a"). This is a set value annotation, since it is a set value, can it be dynamically modified according to different circumstances while the code is running?

The annotations on the field are actually stored in a memberValues property, which is a map, which can be obtained in this way.

Field [] fields = User.class.getDeclaredFields (); for (Field field: fields) {/ / after setting, you can access the private variable if ("age" .equals (field.getName () {field.setAccessible (true); / / get the InvocationHandler InvocationHandler invocationHandler = Proxy.getInvocationHandler (field.getAnnotation (Value.class)) held by the proxy instance annotation / / get the memberValues field of InvocationHandler Field memberValues = invocationHandler.getClass () .getDeclaredField ("memberValues"); memberValues.setAccessible (true); Map values = (Map) memberValues.get (invocationHandler); System.out.println (values);}}

Debug breakpoint, you can see--

This Map stores all the attribute values in the @ annotation. Here, @ Value has only one value attribute--

Public @ interface Value {String value ();}

If you replace it with something like @ JSONField (name= "age_a"), modify the above code slightly, such as:

Field [] fields = User.class.getDeclaredFields (); for (Field field: fields) {if ("age" .equals (field.getName () {field.setAccessible (true); InvocationHandler invocationHandler = Proxy.getInvocationHandler (field.getAnnotation (JSONField.class));. }}

The internal properties of @ JSONField annotations are as follows--

If you run the code just now, you can see that what Map gets and stores here is all the attributes and corresponding attribute values in this annotation.

At this point, go back to the previous question. What do you do if you want to change the value of this annotation dynamically?

In fact, it's very simple, you just need to set the value directly, for example--

InvocationHandler invocationHandler = Proxy.getInvocationHandler (field.getAnnotation (Value.class)); Field memberValues = invocationHandler.getClass (). GetDeclaredField ("memberValues"); memberValues.setAccessible (true); Map values = (Map) memberValues.get (invocationHandler); values.put ("value", "new_age"); memberValues.setAccessible (false)

Just, note that the key here needs to correspond to the attribute values in the comments above.

Fourth, the method and calling mode of reflection getting class.

Object o=User.class.newInstance (); / / the setAge method of User is obtained through reflection. The following String.class indicates the parameter type of the setAge method. If there are multiple, it is listed / / at the same time. For other types, such as List,Long, it is List.class,Long.class Method m = (Method) o.getClass (). GetMethod ("setAge", String.class); m.invoke (o, "name"); User user = (User) o; System.out.println (user)

As can be seen from the print, age is already name, indicating that the setAge call was successful.

This kind of usage scenario is more common among agents.

Finally, a Map-to-object encapsulation tool is implemented through reflection.

Public Object MapToObject (Object object,Map map) throws IllegalAccessException {Class cla = object.getClass (); Field [] fields = cla.getDeclaredFields (); for (Field field:fields) {field.setAccessible (true); if ("serialVersionUID" .equals (field.getName ()) continue; if (map.get (field.getName ())! = null) {Object value=map.get (field.getName () Value=convertValType (value,field.getType ()); field.set (object, value);} return object;} private static Object convertValType (Object value, Class fieldTypeClass) {Object o = null If (Long.class.getName () .equals (fieldTypeClass.getName ()) | | long.class.getName () .equals (fieldTypeClass.getName () {o = Long.parseLong (value.toString ()) } else if (Integer.class.getName () .equals (fieldTypeClass.getName ()) | | int.class.getName () .equals (fieldTypeClass.getName () {o = Integer.parseInt (value.toString ()) } else if (Float.class.getName () .equals (fieldTypeClass.getName ()) | | float.class.getName () .equals (fieldTypeClass.getName () {o = Float.parseFloat (value.toString ()) } else if (Double.class.getName (). Equals (fieldTypeClass.getName ()) | | double.class.getName () .equals (fieldTypeClass.getName () {o = Double.parseDouble (value.toString ());} else {retVal = o;} return retVal } after reading this, the article "Code Analysis of reflection Mechanism examples in Java Development" 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, 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

Internet Technology

Wechat

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

12
Report