Design of map automatic assembly JavaBean tool class based on Java reflection
We usually don’t often need to use map to pass parameters when using Myabtis. The steps are generally as follows:
public List<Role> findRoles(Map<String,Object> param); <select id="dindRoles" parameterType="map" resultType="role"> select id,role_name as roleName,note form t_role where role_name = #{roleName} and note = #{note} </select> //我们常常需要手打这些字段名 Map<String,Object> map = new HashMap<>(); map.put("roleName","xiaoming"); map.put("note","10"); List<Role> roles = roleMapper.findRoles(map);
But if you need to put When there are many fields and each attribute name is very long, it will be uncomfortable. Here you can use Java reflection method to automatically assemble the map. The following is the author's implementation:
public class Test { //实现效果 public static void main(String[] args) { HashMap<String, Object> map = new HashMap<>(); Person person1 = new Person(); person1.setAge(2); person1.setName("foonsu"); //调用写好的mapBuild自动装配 mapBuild(person1, map); //输出效果 for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } public static void mapBuild(Object javaBean, Map map) { Class clazz = javaBean.getClass(); //反射获取 Field[] name = clazz.getDeclaredFields(); for (Field field : name) { //将非null的javaBean属性值装配到map中 if (getGetMethod(javaBean,field.getName())!=null) map.put(field.getName(), getGetMethod(javaBean,field.getName())); } } /** * 根据属性,获取get方法 */ public static Object getGetMethod(Object ob, String name) { Method[] m = ob.getClass().getMethods(); try { for (int i = 0; i < m.length; i++) { if (("get" + name).toLowerCase().equals(m[i].getName().toLowerCase())) { return m[i].invoke(ob); } } } catch (Exception e) { } return null; } } class Person{ int age; String name; String personId; public String getPersonId() { return personId; } public void setPersonId(String personId) { this.personId = personId; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Ps: This is a direct traversal method, and the time complexity is O(N^2), because in actual production, there will not be many designs of a JavaBean attribute. In fact, space replacement can also be used. The idea of time optimizes the method to a time complexity of O(n).
Related recommendations:
java reflection implementation javabean to json example code
java reflection reflection basics
The above is the detailed content of Design of map automatic assembly JavaBean tool class based on Java reflection. For more information, please follow other related articles on the PHP Chinese website!

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
