Java通过反射机制,动态设置对象属性值

1 : 测试截图

Java通过反射机制,动态设置对象属性值_第1张图片

2 : 工具类
package util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import java.lang.reflect.Field;
import java.lang.reflect.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("反射赋值:" + entity.toString());
        System.out.println("反射取值:");
        Map<String, String> fieldValMap = getBeanFieldValue(entity);
        for (Map.Entry<String, String> entry : fieldValMap.entrySet()) {
            System.out.println("字段名:["+entry.getKey()+"],字段值:[" + entry.getValue()+"]");
        }
    }

    /**
     * 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 = bean.getClass();
        Map<String, String> valueMap = new HashMap<String, String>();
        Method[] methods = beanClass.getDeclaredMethods();
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            try {
                String fieldGetMethodName = spliceGetMethod(field.getName());
                if (!checkPropertyMethodExist(methods, fieldGetMethodName)) continue;
                Method fieldGetMethod = beanClass.getMethod(fieldGetMethodName, new Class[] {});
                Object fieldValue = fieldGetMethod.invoke(bean, new Object[] {});
                if(null != fieldValue){
                    if ("Date".equals(field.getType().getSimpleName())) {
                        valueMap.put(field.getName(), DateFormatUtils.format((Date)fieldValue, "yyyy-MM-dd HH:mm:ss"));
                        continue;
                    }
                    valueMap.put(field.getName(), String.valueOf(fieldValue));
                }
            } catch (Exception e) {
                log.error("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 = bean.getClass();
        Method[] methods = beanClass.getDeclaredMethods();
        Field[] fields = beanClass.getDeclaredFields();
        for (Field field : fields) {
            try {
                String fieldSetName = spliceSetMethod(field.getName());
                if (!checkPropertyMethodExist(methods, fieldSetName)) continue;
                Method fieldSetMet = beanClass.getMethod(fieldSetName, field.getType());
                String value = valueMap.get(field.getName());
                fieldSetMet.invoke(bean, getFieldTypeValue(field, value));
            } catch (Exception e) {
                log.error("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 = field.getType().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()).toInstant());
        }
        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.equals(met.getName())) 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
     */
    public 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;

public class InvokeEntity {

    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() {
        return number;
    }

    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 +
                ", work=" + work +
                ", fund=" + fund +
                ", date=" + date +
                ", time=" + time +
                ", dateTime=" + dateTime +
                ", flag=" + flag +
                '}';
    }
}

4 : 参考链接

http://www.itxm.cn/post/2706.html

你可能感兴趣的:(工作总结,反射,java)