Java uses reflection to convert objects into MongoDb structures
Dec 15, 2020 pm 05:30 PMjava Basic TutorialThe column introduces how to convert objects into MongoDb structures
Recommended (free): java Basic Tutorial
Reflection is an advanced technique in Java, which is widely used in various open source projects. For example, Spring, Tomcat, Jetty and other projects all use reflection extensively.
As Java programmers, if we use reflection well, we can not only improve our technical level, but also develop better projects.
However, although many people have heard of reflection, they don’t know where they should be used.
So, we will start from the actual work and use reflection to convert the object into MongoDb data structure. After you understand this example, you will understand how reflection is used.
Requirement Analysis
In the e-commerce system, some data must be saved to MongoDb to improve query performance. But before that, we must first convert the data into MongoDb structure, that is, convert Java objects into Documents.
For example, if order information is to be stored in MongoDb, the order object must be converted into a Document.
But in this way, each entity class must develop a 2Doc() method. This method has no technical content, it just puts various fields into the Document. And once there are too many fields, you will write wrong code if you are not careful. You can feel it.
public?class?Order?{ ????private?Long?id; ????private?Long?userId; ????private?String?orderNo; ????private?BigDecimal?amount; ????private?String?createTime; ????private?String?updateTime; ????//?省略無數(shù)字段 ???? ????//?轉(zhuǎn)換方法:訂單轉(zhuǎn)doc ????public?Document?order2Doc(Order?order)?{ ????????Document?doc?=?new?Document(); ????????doc.put("id",?order.getId()); ????????doc.put("userId",?order.getUserId()); ????????doc.put("orderNo",?order.getOrderNo()); ????????doc.put("amount",?order.getAmount()); ????????doc.put("createTime",?order.getCreateTime()); ????????doc.put("updateTime",?order.getUpdateTime()); ????????//?省略無數(shù)put... ????????return?doc; ????} }
In addition, we have to get the data from MongoDb and convert the Document back to a Java object. You can feel it again.
public?class?Order?{ ????private?Long?id; ????private?Long?userId; ????private?String?orderNo; ????private?BigDecimal?amount; ????private?String?createTime; ????private?String?updateTime; ????//?省略無數(shù)字段 ???? ????//?轉(zhuǎn)換方法:doc轉(zhuǎn)訂單 ????public?Order?doc2Order(Document?doc)?{ ????????Order?order?=?new?Order(); ???????? ????????order.setId((Long)?doc.get("id")); ????????order.setUserId((Long)?doc.get("userId")); ????????order.setOrderNo((String)?doc.get("orderNo")); ????????order.setAmount((BigDecimal)?doc.get("amount")); ????????order.setCreateTime((String)?doc.get("createTime")); ????????order.setUpdateTime((String)?doc.get("updateTime")); ????????//?省略無數(shù)set... ????????return?order; ????} }
Just one order class is so troublesome, not to mention there are more than one such class, and the project always has new requirements. If one field is changed, you will be in big trouble, and you may have to turn over the entire project. Again.
Therefore, in order to reduce errors, these two conversion methods must be optimized, and this optimization uses two advanced features of Java: reflection and generics. In order to give everyone a more intuitive understanding, I will divide it into two version iterations.
The first version uses reflection to simplify the conversion method of entity classes;The second version uses generics and reflection to extract MongoDb tool classes;
Next, Let’s iterate step by step~
Use reflection to simplify the conversion methods of entity classes
In the first version of iteration, we want to simplify the two conversion methods of entity classes.
Let’s start by converting Java objects to Documents, taking the Order class as an example.
First, we obtain all the field information of the order class through reflection; then, we use a loop to traverse these fields; finally, in the loop, we release the access rights of the fields and put the fields into the Document.
public?class?Order?{ ????//?...省略無數(shù)字段 ????public?Document?order2Doc(Order?order)?throws?Exception?{ ????????Document?doc?=?new?Document(); ????????//?獲取所有字段:通過?getClass()?方法獲取?Class?對象,然后獲取這個類所有字段 ????????Field[]?fields?=?order.getClass().getDeclaredFields(); ????????for?(Field?field?:?fields)?{ ????????????//?開放字段操作權(quán)限 ????????????field.setAccessible(true); ????????????//?設(shè)置值 ????????????doc.put(field.getName(),?field.get(order)); ????????} ????????return?doc; ????} }
You can see that after reflection transformation, the code is much simpler. No matter how many fields an object has or how many put operations need to be written, it can be done with just these few lines of code. Converting Java objects into MongoDb structures seems less cumbersome.
Following this idea, let’s transform the second method, convert Document to Java object.
public?class?Order?{ ????//?...省略無數(shù)字段 ????public?Order?doc2Order(Document?doc)?throws?Exception?{ ????????Order?order?=?new?Order(); ????????for?(String?key?:?doc.keySet())?{ ????????????//?獲取字段 ????????????Field?field?=?order.getClass().getDeclaredField(key); ????????????//?開放字段操作權(quán)限 ????????????field.setAccessible(true); ????????????//?設(shè)置值 ????????????field.set(order,?doc.get(key)); ????????} ????????return?order; ????} }
First, we use a loop to traverse the Document; in the loop, use reflection to obtain the corresponding fields, then release the access rights of the fields, and set the value of the Document to the fields of the object.
At this point, we used reflection to simplify the conversion method of the two entity classes, and the first version of iteration is basically completed. The remaining work is to copy and paste and reshape each class.
However, after this iteration, although a lot of work has been reduced, there are still many unreasonable places.
First of all, there are still a lot of duplicate codes. Each entity class has two conversion methods, but the core logic of these two methods is the same, so there is no need to copy them everywhere.
Then, this is not a function that entity classes should undertake. Entity classes are only responsible for temporarily retaining data and are not responsible for any persistence functions. Where you store the data and what data structure it should be converted into has nothing to do with entity classes.
In other words, we have to do a second iteration.
Use generics and reflection to extract MongoDb tool classes
Simply put, generics are a style or paradigm. You don’t need to specify the specific parameter type at the beginning, but use Then determine the parameter type.
If we combine generics and reflection, it can help us reduce a lot of duplicate code.
Let’s see, how to do the second iteration?
Start by converting Java objects to Document. We first declare a generic method; then, through reflection, obtain all field information of the generic class, and then use a loop to traverse these fields; finally, in the loop, put the fields into the Document.
public?class?MongoDbUtils?{ ????//?定義泛型方法: ????//?1.?在返回值前,聲明泛型參數(shù)?<參數(shù)名>; ????//?2.?傳入?yún)?shù)時,指定一個泛型參數(shù) ????public?static?<T>?Document?obj2Doc(T?obj)?throws?Exception?{ ????????Document?doc?=?new?Document(); ????????//?獲取所有字段:通過?getClass()?方法獲取?Class?對象,然后獲取這個類所有字段 ????????Field[]?fields?=?obj.getClass().getDeclaredFields(); ????????for?(Field?field?:?fields)?{ ????????????//?開放字段操作權(quán)限 ????????????field.setAccessible(true); ????????????//?設(shè)置值 ????????????doc.put(field.getName(),?field.get(obj)); ????????} ????????return?doc; ????} }
After adding generics, duplicate code has been greatly reduced, and entity classes no longer need to write a separate 2Doc()
method. When using it, just call MongoDbUtils.obj2Doc()
.
Following the same idea, we continue to transform the second method, Document to Java object.
public?class?MongoDbUtils?{ ????//?定義泛型方法: ????//?1.?在返回值前,聲明泛型參數(shù)?<參數(shù)名>; ????//?2.?傳入?yún)?shù)必須是?Class,但這個?Class?是泛型參數(shù),不限制類型 ????public?static?<T>?T?doc2Obj(Document?doc,?Class<T>?clazz)?throws?Exception?{ ????????//?實例化泛型對象 ????????T?obj?=?clazz.newInstance(); ????????for?(String?key?:?doc.keySet())?{ ????????????//?獲取字段 ????????????Field?field?=?clazz.getDeclaredField(key); ????????????//?開放字段操作權(quán)限 ????????????field.setAccessible(true); ????????????//?設(shè)置值 ????????????field.set(obj,?doc.get(key)); ????????} ????????return?obj; ????} }
首先,我們定義實例化一個泛型對象;然后,我們使用循環(huán)遍歷 Document;最后,在循環(huán)中,使用反射獲取相應(yīng)的字段,把 Document 的值設(shè)置到泛型對象的字段里。
第二版的迭代就基本完成了。我們在第一版迭代的基礎(chǔ)上,加入了泛型,得到了一個工具類 MongoDbUtils
,這個工具類得到結(jié)果和以前完全一樣,你可以看下測試代碼。
public?static?void?main(String[]?args)?throws?Exception?{ ????Order?order?=?new?Order(); ????order.setId(0L); ????order.setUserId(0L); ????order.setOrderNo("1"); ????order.setAmount(new?BigDecimal("0")); ????order.setCreateTime("2"); ????order.setUpdateTime("3"); ????System.out.println("原始數(shù)據(jù):"?+?order); ????Document?document?=?MongoDbUtils.obj2Doc(order); ????System.out.println("轉(zhuǎn)換doc數(shù)據(jù):"?+?document); ????Order?order1?=?MongoDbUtils.doc2Obj(document,?Order.class); ????System.out.println("轉(zhuǎn)換java數(shù)據(jù):"?+?order1); } 運行結(jié)果: 原始數(shù)據(jù):Order(id=0,?userId=0,?orderNo=1,?amount=0,?createTime=2,?updateTime=3) 轉(zhuǎn)換doc數(shù)據(jù):Document{{id=0,?userId=0,?orderNo=1,?amount=0,?createTime=2,?updateTime=3}} 轉(zhuǎn)換java數(shù)據(jù):Order(id=0,?userId=0,?orderNo=1,?amount=0,?createTime=2,?updateTime=3)
這樣一來,我們就不用保留實體類上的轉(zhuǎn)換方法了,剩下的工作就是刪代碼。
MongoDb 和 Java 對象的互相轉(zhuǎn)換就完成了。我們做了兩次迭代,第一次迭代利用了反射,把大量手動 set/get 操作給去掉了;第二次迭代在原來的基礎(chǔ)上,加入了泛型的應(yīng)用,又去掉了一堆重復(fù)代碼。
The above is the detailed content of Java uses reflection to convert objects into MongoDb structures. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Useembeddingwhentherelationshipisone-to-few,dataisaccessedtogether,andfastreadsareneeded;2.Usereferencingwhendealingwithone-to-manyormany-to-manyrelationships,largeorindependentlyquerieddata;3.Considerread/writefrequency,datagrowth,independentqueries

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c
