ITPub博客

首页 > > > 利用反射给JAVABEAN实例赋值

利用反射给JAVABEAN实例赋值

作者:longmanma 时间:2019-12-31 09:32:08 0 删除 编辑

为简化和统一,需要给javabean实例统一赋值,实现代码如下(已测试)

import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import com.xxx.entity.Call;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;publicclass ReflectUtils {

@SuppressWarnings("rawtypes")

publicstaticMap getPoJoFiled(Class cls){

Map names=newHashMap ();

Field[] fileds=cls.getDeclaredFields();

for(Field filed:fileds){

names.put(filed.getName(), filed.getType());

}

return names;

}

@SuppressWarnings("rawtypes")

publicstaticList getSetMethodName(Class cls){

List methodNames=newArrayList ();

Method[] methods =cls.getDeclaredMethods();

for(Method method:methods){

if(method.getName().startsWith("set")){

methodNames.add(method.getName());

}

}

returnmethodNames; }

private static String getMethodNameByField(List methodNames, String filedName) { for (String method : methodNames) { if (method.toLowerCase().equalsIgnoreCase("set" + filedName)) { return method; } } return ""; }

@SuppressWarnings({ "unchecked", "rawtypes" })

publicstaticvoidinitInstance(Object instance,String param)throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{

Class cls=instance.getClass();

Map fieldNames=ReflectUtils.getPoJoFiled(cls);

List methodNames=ReflectUtils.getSetMethodName(cls);

for(Entry field:fieldNames.entrySet()){

String filedName=field.getKey();

String methodName=getMethodNameByField(methodNames,filedName);

Method setMethodName = cls.getMethod(methodName, fieldNames.get(filedName));

String type=fieldNames.get(filedName).getName();

if(type.equals("java.lang.String")) {

setMethodName.invoke(instance, new Object[] {param});

}

elseif(type.equals("int") || type.equals("java.lang.Integer")) {

setMethodName.invoke(instance, newObject[] {new Integer(param)});

}

elseif(type.equals("long") || type.equals("java.lang.Long")) {

setMethodName.invoke(instance, newObject[] {new Long(param)});

}else if (type.equals("float") || type.equals("java.lang.Float")) {

setMethodName.invoke(instance, new Object[]{new Float(param)});

} else if(type.equals("boolean") || type.equals("java.lang.Boolean")) {

setMethodName.invoke(instance, new Object[] { Boolean.valueOf(param) });

}

elseif(type.equals("java.util.Date")) {

Date date = DateUtil.parseDateTime(param);

if(date!=null)

setMethodName.invoke(instance, new Object[] {date});

}

}

}

publicstaticvoidmain(String[] args)throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

String param="20";

Call call=new Call();

initInstance(call,param);

System.out.println(call.toString());

}

 需要用到的公共类:

import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;publicclass DateUtil {

/** * 得到当前的时间,自定义时间格式 y 年 M 月 d 日 H 时 m 分 s 秒

* @param dateFormat 输出显示的时间格式

* @return*/publicfinalstaticString defaultFormat = "yyyy-MM-dd HH:mm:ss";

publicstatic String getCurrentDate(String dateFormat) {

SimpleDateFormat sdf =new SimpleDateFormat(dateFormat);

returnsdf.format(new Date());

}

publicstatic Date parseDateTime(String date){

SimpleDateFormat formatter =new SimpleDateFormat(defaultFormat);

Date newDate =null;

try {

newDate = formatter.parse(date);

} catch (ParseException e) {

e.printStackTrace();

}

return newDate;

}

}

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2730/viewspace-3164002/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-12-18

  • 博文量
    492
  • 访问量
    11986