Skip to content

Instantly share code, notes, and snippets.

@xujiaji
Last active May 16, 2018 04:59
Show Gist options
  • Select an option

  • Save xujiaji/b3f79aa3dcab0c3f2c1783e7d3fead2d to your computer and use it in GitHub Desktop.

Select an option

Save xujiaji/b3f79aa3dcab0c3f2c1783e7d3fead2d to your computer and use it in GitHub Desktop.
一个通过反射和Map为实体类赋值的工具:https://github.com/JustinSDK/JavaSE6Tutorial/blob/master/docs/CH16.md
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;
}
}
@xujiaji
Copy link
Author

xujiaji commented May 16, 2018

public class Student {
    private String name;
    private int score; 

    public Student() {
        name = "N/A"; 
    } 

    public Student(String name, int score) { 
        this.name = name; 
        this.score = score; 
    } 

    public void setName(String name) {
        this.name = name;
    }
    
    public void setScore(int score) {
        this.score = score;
    }

    public String getName() { 
        return name; 
    } 

    public int getScore() { 
        return score; 
    } 

    public String toString() {
        return name + ":" + score;
    }
} 

测试

class BeanUtilDemo
{
    public static void main(String[] args) throws Exception
    {
        Map<String, Object> request = new HashMap<>();
        request.put("name", "caterpillar");
        request.put("score", 90);
        Object obj = BeanUtil.getCommand(request, "com.xujiaji.test.classloadertest.Student");
        System.out.println(obj);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment