Home >Java >javaTutorial >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!