Java通过反射机制,动态设置对象属性值1 : 测试截图
2 : ⼯具类
package util;
slf4j.Slf4j;
import org.apachemons.lang.time.DateFormatUtils;
import flect.Field;
import flect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class InvokeUtil {
public static void main(String[] args){
Map<String, String> valMap =new HashMap<String, String>();
valMap.put("name","测试");
valMap.put("statue","a");
valMap.put("age","23");
valMap.put("height","173.5");
valMap.put("weight","53.7");
valMap.put("amount","573");
valMap.put("number","1");
valMap.put("work","2");
valMap.put("fund","4.1");
valMap.put("date","2021-12-31");
valMap.put("time","2021-12-31 23:34:11");
valMap.put("dateTime","1618560281465");
valMap.put("flag","false");
InvokeEntity entity =new InvokeEntity();
setBeanFieldValue(entity, valMap);
System.out.println("反射赋值:"+ String());
System.out.println("反射取值:");
Map<String, String> fieldValMap =getBeanFieldValue(entity);
for(Map.Entry<String, String> entry : Set()){
System.out.println("字段名:["+Key()+"],字段值:["+ Value()+"]");
}
}
* get bean field value to value map
* @param bean java bean
* @return value map K:field V:value
*/
public static Map<String, String>getBeanFieldValue(Object bean){
Class<?> beanClass = Class();
Map<String, String> valueMap =new HashMap<String, String>();
Method[] methods = DeclaredMethods();
Field[] fields = DeclaredFields();
for(Field field : fields){
try{
String fieldGetMethodName =Name());
if(!checkPropertyMethodExist(methods, fieldGetMethodName))continue;
Method fieldGetMethod = Method(fieldGetMethodName,new Class[]{});
Object fieldValue = fieldGetMethod.invoke(bean,new Object[]{});
if(null != fieldValue){
if("Date".Type().getSimpleName())){
valueMap.Name(), DateFormatUtils.format((Date)fieldValue,"yyyy-MM-dd HH:mm:ss"));
continue;
}
valueMap.Name(), String.valueOf(fieldValue));
}
}catch(Exception e){
<("get bean value error"+ field, e);
}
}
return valueMap;
}
/**
* set bean field value by value map
* @param bean java bean
* @param valueMap value map K:field V:value
*/
public static void setBeanFieldValue(Object bean, Map<String, String> valueMap){
Class<?> beanClass = Class();
Method[] methods = DeclaredMethods();
Field[] fields = DeclaredFields();
for(Field field : fields){
try{
String fieldSetName =Name());
if(!checkPropertyMethodExist(methods, fieldSetName))continue;
Method fieldSetMet = Method(fieldSetName, Type());
String value = (Name());
fieldSetMet.invoke(bean,getFieldTypeValue(field, value));
}catch(Exception e){
<("set bean value error"+ field, e);
}
}
}
/**
* return the corresponding type value according to the field property
* @param field the field
* @param value original value
* @return corresponding type value
*/
public static Object getFieldTypeValue(Field field, Object value){
if(null == field || null == value ||"".equals(value))return null;
String fieldType = Type().getSimpleName();
if("String".equals(fieldType))return String.valueOf(value);
if("Date".equals(fieldType)){
if(String.valueOf(value).indexOf(':')>0)return Date.from(LocalDateTime.parse(String.valueOf(value), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).atZone(ZoneId.systemDefault()).toInstant());
return Date.from(LocalDate.parse(String.valueOf(value), DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay(ZoneId.systemDefault()).toIns tant());
}
if("Integer".equals(fieldType)||"int".equals(fieldType))return Integer.parseInt(String.valueOf(value));
if("Long".equalsIgnoreCase(fieldType))return Long.parseLong(String.valueOf(value));
if("Float".equalsIgnoreCase(fieldType))return Float.parseFloat(String.valueOf(value));
if("Double".equalsIgnoreCase(fieldType))return Double.parseDouble(String.valueOf(value));
if("Short".equalsIgnoreCase(fieldType))return Short.parseShort(String.valueOf(value));
if("Byte".equalsIgnoreCase(fieldType))return Byte.parseByte(String.valueOf(value));
if("BigDecimal".equalsIgnoreCase(fieldType))return new BigDecimal(String.valueOf(value));
if("Character".equals(fieldType)||"char".equals(fieldType))return String.valueOf(value).charAt(0);
if("Boolean".equalsIgnoreCase(fieldType))return Boolean.parseBoolean(String.valueOf(value));
if("TimeStamp".equalsIgnoreCase(fieldType))return new Timestamp(Long.valueOf(String.valueOf(value)));
return value;
}
/**
* judge whether it exists method of a property
* @param methods object property method list
* @param fieldMethod get or set method
* @return true: exist, false: not exist
*/
public static boolean checkPropertyMethodExist(Method[] methods, String fieldMethod){
if(null == fieldMethod ||"".equals(fieldMethod))return false;
for(Method met : methods){
if(fieldMethod.Name()))return true;
}
return false;
}
/**
* splicing property get or set methods
* @param fieldName property name
* @param method get or set method
* @return methods after splicing
*/
public static String splicePropertyMethod(String fieldName, String method){
if(null == fieldName ||"".equals(fieldName))return null;
return method + fieldName.substring(0,1).toUpperCase()+ fieldName.substring(1);
}
/**
* splicing property get method
* @param fieldName property
* @return get method after splicing
*/
java valueofpublic static String spliceGetMethod(String fieldName){
return splicePropertyMethod(fieldName,"get");
}
/
**
* splicing property set method
* @param fieldName property
* @return set method after splicing
*/
public static String spliceSetMethod(String fieldName){
return splicePropertyMethod(fieldName,"set");
}
}
3 : 测试Bean
package util;
import java.sql.Timestamp;
import java.math.BigDecimal;
import java.util.Date;
private String name;
private Character statue;
private Integer age;
private Float height;
private Double weight;
private Long amount;
private Short number;
private Byte work;
private BigDecimal fund;
private Date date;
private Date time;
private Timestamp dateTime;
private boolean flag;
public String getName(){
return name;
}
public void setName(String name){ this.name = name;
}
public Character getStatue(){
return statue;
}
public void setStatue(Character statue){ this.statue = statue;
}
public Integer getAge(){
return age;
}
public void setAge(Integer age){ this.age = age;
}
public Float getHeight(){
return height;
}
public void setHeight(Float height){ this.height = height;
}
public Double getWeight(){
return weight;
}
public void setWeight(Double weight){ this.weight = weight;
}
public Long getAmount(){
return amount;
}
public void setAmount(Long amount){ this.amount = amount;
}
public Short getNumber(){
}
public void setNumber(Short number){
this.number = number;
}
public Byte getWork(){
return work;
}
public void setWork(Byte work){
this.work = work;
}
public BigDecimal getFund(){
return fund;
}
public void setFund(BigDecimal fund){
this.fund = fund;
}
public Date getDate(){
return date;
}
public void setDate(Date date){
this.date = date;
}
public Date getTime(){
return time;
}
public void setTime(Date time){
this.time = time;
}
public Timestamp getDateTime(){
return dateTime;
}
public void setDateTime(Timestamp dateTime){ this.dateTime = dateTime;
}
public boolean isFlag(){
return flag;
}
public void setFlag(boolean flag){
this.flag = flag;
}
@Override
public String toString(){ return"InvokeEntity{"+
"name='"+ name +'\''+
", statue="+ statue +
", age="+ age +
", height="+ height +
", weight="+ weight +
", amount="+ amount +
", number="+ number +

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。