public classReflectGetValueUtils {
/**
* 取出bean 属性和值
*
*@paramobj
*@return
*@throwsException
*/
public staticMap getFileValue(Object obj) {
Map map =newHashMap();
try{
Class cls = obj.getClass();
Method methods[] = cls.getDeclaredMethods();
Field fields[] = cls.getDeclaredFields();
for(Field field : fields) {
String fldtype = field.getType().getSimpleName();
String getMetName =pareGetName(field.getName());
String result ="";
if(!checkMethod(methods, getMetName)) {
continue;
}
Method method = cls.getMethod(getMetName,newClass[] { field.getType() });
Object object =null;
object = method.invoke(obj,newObject[]{});
if(null!= object) {
if(fldtype.equals("Date")) {
result =fmlDate((Date) object);
}
result = String.valueOf(object);
}
map.put(field.getName(), result);
}
}catch(Exception e) {
e.printStackTrace();
}
returnmap;
}
/**
* 设置bean 属性值
*
*@parammap
*@parambean
*@throwsException
*/
public static voidsetFieldValue(Map map, Object bean) {
try{
Class cls = bean.getClass();
Method methods[] = cls.getDeclaredMethods();
Field fields[] = cls.getDeclaredFields();
for(Field field : fields) {
String fldtype = field.getType().getSimpleName();
String fldSetName = field.getName();
String setMethod =pareSetName(fldSetName);
if(!checkMethod(methods, setMethod)) {
continue;
}
Object value = map.get(fldSetName);
// System.out.println(value.toString());
Method method = cls.getMethod(setMethod, field.getType());
// System.out.println(method.getName());
if(null!= value) {
if("String".equals(fldtype)) {
method.invoke(bean, (String) value);
}else if("Double".equals(fldtype)) {
method.invoke(bean, (Double) value);
}else if("int".equals(fldtype)) {
intval = Integer.valueOf((String) value);
method.invoke(bean, val);
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* 拼接某属性get 方法
*
*@paramfldname
*@return
*/
public staticString pareGetName(String fldname) {
if(null== fldname ||"".equals(fldname)) {
return null;
}
String pro ="get"+ fldname.substring(0,1).toUpperCase() + fldname.substring(1);
returnpro;
}
/**
* 拼接某属性set 方法
*
*@paramfldname
*@return
*/
public staticString pareSetName(String fldname) {
if(null== fldname ||"".equals(fldname)) {
return null;
}
String pro ="set"+ fldname.substring(0,1).toUpperCase() + fldname.substring(1);
returnpro;
}
/**
* 判断该方法是否存在
*
*@parammethods
*@parammet
*@return
*/
public static booleancheckMethod(Method methods[], String met) {
if(null!= methods) {
for(Method method : methods) {
if(met.equals(method.getName())) {
return true;
}
}
}
return false;
}
/**
* 把date 类转换成string
*
*@paramdate
*@return
*/
public staticString fmlDate(Date date) {
if(null!= date) {
SimpleDateFormat sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
returnsdf.format(date);
}
return null;
}
}
网友评论