How to get the value of a generic field in Java

1. Scenario review

An entity class of type Object is passed in a method, how do we get the value of user's id in this method?

insert image description here

method one

Using Java's reflection principle

 Field idField = obj.getClass().getDeclaredField("id");
 idField.setAccessible(true);
 String id1 = (String) idField.get(obj);

Method Two

Conversion using JSON objects

 String str = JSON.toJSONString(obj);
 JSONObject jsonObject = JSON.parseObject(str);
 String id2 = jsonObject.getString("id");

Map to Entity

Map<String, Object> authorMap = new HashMap<>();
     authorMap.put("id", 10L);
     authorMap.put("name", "蜡笔小新");
     authorMap.put("category", "分类");
     authorMap.put("score", 90);
     authorMap.put("intro", "简介");
     Book book = JSON.parseObject(JSON.toJSONString(authorMap), Book.class);
     System.out.println(book);

Entity to Map

Book book1 = new Book();
book1.setId(1l);
book1.setName("风间");
book1.setCategory("分类");
book1.setIntro("简介");
book1.setScore(100);
Map map = JSON.parseObject(JSON.toJSONString(book1), Map.class);
System.out.println(map);

Introduce dependencies

<dependency>
   <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.54</version>
</dependency>

Guess you like

Origin blog.csdn.net/yy12345_6_/article/details/130772262