String str ="name=xiaomaha,password=123456,date=2007-05-20"
格式(=号前面的字符串必须和下面代码的属性对应)
private Integer id;
private String name;
private String password;
private Date date;
POJO
package com.xiaomaha.po;
import java.util.Date;
/**
* User generated by MyEclipse Persistence Tools
*/
public class User implements java.io.Serializable {
// Fields
private Integer id;
private String name;
private String password;
private Date date;
// Constructors
/** default constructor */
public User() {
}
/** minimal constructor */
public User(String name) {
this.name = name;
}
/** full constructor */
public User(String name, String password, Date date) {
this.name = name;
this.password = password;
this.date = date;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDate() {
return this.date;
}
public void setDate(Date date) {
this.date = date;
}
}
我写了个这个工具类来实现动态产生对象并且赋值``但我测试过10000次大概需要1秒``希望高手能帮我优化下``我感觉自己写的很烂!
工作中需要用的!
/**
*
* @param bean JavaBean标准,类名
* @param str 以字符传形式传递,与bean属性相同`不区分大小写
* @return 返回bean实例,需要强转
*/
public static Object createObject(Class bean, String str) throws Exception,
Exception {
Method[] m = bean.getMethods();
Object obj = bean.newInstance();
String[] ss = str.split(",");
for (int j = 0; j < ss.length; j++) {
String[] sts = ss[j].split("=");
for (int i = 0; i < m.length; i++) {
if (m[i].getName().startsWith("set")) {
if(m[i].getName().substring(3, m[i].getName().length()).equalsIgnoreCase(sts[0])){
Class[] cl = m[i].getParameterTypes();
for (int k = 0; k < cl.length; k++) {
if (cl[k].getName().equals("int")
|| cl[k].getName().equals(
"java.lang.Integer")){
m[i].invoke(obj, new Integer(sts[1]));
}
if (cl[k].getName().equals("java.lang.String")){
m[i].invoke(obj, sts[1]);
}
if (cl[k].getName().equals("java.util.Date")){
m[i].invoke(obj, getTheTime(sts[1]));
}
if (cl[k].getName().equals("java.sql.Date")){
m[i].invoke(obj, getTheTime(sts[1]));
}
}
}
}
}
}
return obj;
}
/**
*
* @param date 字符类型转日期类型
* @return 返回yyyy-MM-dd 格式日期类型
*/
public static Date getTheTime(String date) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date cDate = null;
Date dd = null;
try {
cDate = df.parse(date);
dd = new java.sql.Date(cDate.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return dd;
}