问题描述
- 通过类反射获取实体类对象
-
private String[] colName = null; // 属性名数组数组 private String[] colType = null; // 存放实体类的数据类型 如java.lang.Long private String[] colValue = null; // 要存进去的值
请问一下我有一个实体类 要把colValue里的数据以colType类型存到TbUser实体类的属性里 并且返回这个实体类 的对象 请大神给个思路 。。。 多谢
解决方案
如果colType仅仅是简单类型,那么最简单的是直接switch类型然后用 xxx.parseXXX() 解析字符串就可以了
http://longzhun.iteye.com/blog/1084362
解决方案二:
package com.reflect;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
public class ReflectSetObject {
static class TbUser {
private int userId;
private String userName;
private String userPassword;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "userId = " + userId + " ,userName = "+userName+ " ,userPassword = "+userPassword;
}
}
/**
* 未用colType,因Class c = Class.forName(colType[i]); c.cast(colValue[i])对int不行
* @param cls
* @param colName
* @param colType
* @param colValue
* @return
*/
public <T> T setObject(Class<T> cls, String[] colName, String[] colType, String[] colValue){
T t = null;
try {
t = cls.newInstance();
BeanInfo info = Introspector.getBeanInfo(cls);
PropertyDescriptor[] pros = info.getPropertyDescriptors();
for (PropertyDescriptor pro : pros) {
String pname = pro.getName();
for(int i=0; i<colName.length ;i++){
if(pname.equals(colName[i])){
try {
// Class c = Class.forName(colType[i]);
// c.cast(colValue[i]);
Class<?> c = pro.getPropertyType();
if(c == java.lang.Integer.class || c == int.class){
pro.getWriteMethod().invoke(t, java.lang.Integer.valueOf(colValue[i]));
break;
}else if(c == java.lang.String.class){
pro.getWriteMethod().invoke(t, colValue[i]);
break;
}else{
break;
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return t;
}
public static void main(String[] args){
ReflectSetObject s = new ReflectSetObject();
TbUser u = s.setObject(TbUser.class, new String[]{"userId","userName","userPassword"},
null, new String[]{"123", "zhansan", "123"});
System.out.println(u);
}
}
用JavaBean自省,可以实现但不建议你这么操作。看你这个像是数据库操作。