Java reflection to get an object attribute value code analysis
Sometimes you know what's inside the object, but for various reasons, you can't convert it into an object. You just want to simply pick up some things in the object. At this time, you need to use reflection.
If your class is like this:
We create a new one, assign a value, and transform it upward into an object
Get the property name and save it with an array
output
12-17 12:02:10.199 22949-22949/com. example. wechat I/xbh: this$0 12-17 12:02:10.199 22949-22949/com. example. wechat I/xbh: userName 12-17 12:02:10.199 22949-22949/com. example. wechat I/xbh: userPassword 12-17 12:02:10.199 22949-22949/com. example. wechat I/xbh: $change 12-17 12:02:10.199 22949-22949/com. example. wechat I/xbh: serialVersionUID
You can see that there are two attribute names defined by us. Forget the other three
To get the property value, first get the get method, and then call the get method to get it
Output 12-17 12:09:33.429 29677-29677/com example. Wechat I / XBH: Xu Fenglai 12-17 12:09:33.429 29677-29677/com example. wechat I/xbh: 1596666
The if statement is the method to get the beginning of get
Invoke in try executes this method and puts the return value in o
Property values are not obtained through the get method
Output 12-17 12:17:34.419 4732-4732/com example. Wechat I / XBH: Xu Fenglai
You can get it directly through the getdeclaredfield method (note that it is different from the getdeclaredfields method above). However, if your property is private, you can't access it, so you can access it by setting this property to public (setaccessible).
In addition, if you get JSON data, you don't need to parse an object in it. You can directly transform it into a map.
such as
{"code":0,"list":[{"userName":"3294727437","userPassword":"xbh1","userAvatar":" https://img1.imgtn.bdimg.com/it/u \u003d37460727\u0026gp\u003d0. jpg"}]}
You get the following collections through jsonarray ("list"), and then get a single object through get (I). In fact, the initial object is converted into a map. Take a closer look. Therefore, you don't need to reflect to obtain properties, and you can directly convert it into a map to get data.
as
summary
The above is all about the code analysis of java reflection to obtain an object attribute value. I hope it will be helpful to you. Interested friends can continue to refer to other related topics on this site. If there are deficiencies, please leave a message to point out. Thank you for your support!