Last active
May 16, 2018 04:59
-
-
Save xujiaji/b3f79aa3dcab0c3f2c1783e7d3fead2d to your computer and use it in GitHub Desktop.
一个通过反射和Map为实体类赋值的工具:https://github.com/JustinSDK/JavaSE6Tutorial/blob/master/docs/CH16.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class BeanUtil | |
| { | |
| public static Object getCommand(Map<String, Object> requestMap, | |
| String commandClass) | |
| throws Exception | |
| { | |
| Class c = Class.forName(commandClass); | |
| Object o = c.newInstance(); | |
| return updateCommand(requestMap, o); | |
| } | |
| public static Object updateCommand( | |
| Map<String, Object> requestMap, | |
| Object command) | |
| throws Exception | |
| { | |
| Method[] methods = | |
| command.getClass().getDeclaredMethods(); | |
| for (Method method : methods) | |
| { | |
| // 过滤private和protected,并且set开头的方法 | |
| if (!Modifier.isPrivate(method.getModifiers()) && | |
| !Modifier.isProtected(method.getModifiers()) && | |
| method.getName().startsWith("set")) | |
| { | |
| String name = method.getName() | |
| .substring(3) | |
| .toLowerCase(); | |
| if (requestMap.containsKey(name)) | |
| { | |
| method.invoke(command, requestMap.get(name)); | |
| } | |
| } | |
| } | |
| return command; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
测试