经过历时三天的鏖战,终于将阶段性项目——新闻发布系统做完了。在编码过程中,发现了很多冗余代码,统一流程,却需要不断重复编码——将用户输入实例化为对象的过程。
例:
Person.set("id", 1);
Person.set("name", "hu");
Person.set("birthday", new Date());
基于此我将该过程中间过程抽离出来,采用反射机制,遍历所有属性名获取对应的值,并将其放进实例化对象,达到封装不变部分的目的。
话不多说直接上代码:
Person.java
package com.blk.entity; import java.util.Date; public class Person { private int pid; private String name; private Date birthday; public Person() { super(); } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "Person [birthday=" + birthday + ", name=" + name + ", pid=" + pid + "]"; } }
ToBean.java
package com.blk.demo; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.blk.dao.ToBean; import com.blk.entity.Person; public class Test { public static void main(String[] args) throws InstantiationException, IllegalAccessException { // 创建map对象,并进行数据 Map<String, Object> map = new HashMap<String, Object>(); map.put("pid", 1); map.put("name", "hu"); map.put("birthday", new Date()); // 将map对象转化为实体类对象 Person p = (Person)ToBean.toBean(map, Person.class); System.out.println(p.toString()); } }
测试代码:Test.java
package com.blk.demo; import java.util.Date; import java.util.HashMap; import java.util.Map; import com.blk.dao.ToBean; import com.blk.entity.Person; public class Test { public static void main(String[] args) throws InstantiationException, IllegalAccessException { // 创建map对象,并进行数据 Map<String, Object> map = new HashMap<String, Object>(); map.put("pid", 1); map.put("name", "hu"); map.put("birthday", new Date()); // 将map对象转化为实体类对象 Person p = (Person)ToBean.toBean(map, Person.class); System.out.println(p.toString()); } }