当前位置: 代码迷 >> 综合 >> 使用反射给属性赋值.
  详细解决方案

使用反射给属性赋值.

热度:3   发布时间:2024-02-06 03:23:04.0

利用反射机制给属性赋值并输出.

import java.lang.Class;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Date;
import java.text.SimpleDateFormat;public class Test{public static void main(String[] args){String str = "name:zhangsan|age:lisi|res:true|salary:13000:99|entryTime:2020-08-22";User user = ClassInstanceFactory.create(User.class,str);System.out.println("名称:" + user.getName() + "---年龄:"+ user.getAge() + "---状态:" +user.getRes() +"---薪水:"+user.getSalary() + "---时间:" +user.getEntryTime());//App.test();}
}class StringUtils{public static String inticap(String value){if(value == null || "".equals(value)){return value;}if(value.length() == 1){return value.toUpperCase();}else{return value.substring(0,1).toUpperCase() + value.substring(1);}}
}class BeanUtils{public static void init(Object object,String value){String result[] = value.split("\\|");for(int i=0; i<result.length; i++){try{String val[] = result[i].split(":");Field field = object.getClass().getDeclaredField(val[0]);Method method = object.getClass().getDeclaredMethod("set"+StringUtils.inticap(val[0]),field.getType());Object obj = convertTyep(field.getType().getName(),val[1]);method.invoke(object,obj);}catch(Exception e){}}}public static Object convertTyep(String type,String value){if("long".equals(type) || "java.long.Long".equals(type)){return Long.parseLong(value);}else if("int".equals(type) || "java.long.Integer".equals(type)){return Integer.parseInt(value);}else if("boolean".equals(type) || "java.long.Boolean".equals(type)){return Boolean.parseBoolean(value);}else if("double".equals(type) || "java.long.Double".equals(type)){return Double.parseDouble(value);}else if("java.util.Date".equals(type)){SimpleDateFormat sdf = null;if(value.matches("\\d{4} - \\d{2} - \\d{2}")){sdf = new SimpleDateFormat(value);}else if(value.matches("\\d{4} - \\d{2} - \\d{2} \\d{2} : \\d{2} : \\d{2}")){sdf = new SimpleDateFormat(value);}else{return new Date();}return sdf;}else{return value;}}}class ClassInstanceFactory{private ClassInstanceFactory(){}public static <T> T create(Class<?> clazz,String value){try{Object object = clazz.newInstance();BeanUtils.init(object,value);return (T)object;	}catch(Exception e){return null;}}
}class User{private String name;private int age;private boolean res;private double salary;private Date entryTime;public void setName(String name){this.name = name;}public String getName(){return this.name;}public void setAge(int age){this.age = age;}public int getAge(){return this.age;}public void setRes(boolean res){this.res = res;}public Boolean getRes(){return this.res;}public void setSalary(double salary){this.salary = salary;}public Double getSalary(){return this.salary;}public void setEntryTime(Date entryTime){this.entryTime = entryTime;}public Date getEntryTime(){return this.entryTime;}
}
  相关解决方案