JAVA利用反射为对象赋值

如题

/**
 * @author: 骑猪撞地球QAQ
 * @date: 2021/03/17 11:26
 * @content:
 */
public class SetClassUtil {
    
    
	/**
     * 用于对类的字段赋值,无视private,project修饰符,无视set/get方法
     * @param c 要反射的类
     * @param list 类的字段名和值 每个字段名和值用英文逗号隔开
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Object setClassFileValue(Class c, List<String> list) {
    
    
        try {
    
    
            Object object = Class.forName(c.getName()).newInstance();
            Class<?> obj = object.getClass();
            Field[] fields = obj.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
    
    
                fields[i].setAccessible(true);
                for (int j = 0; j < list.size(); j++) {
    
    
                    String str = list.get(j);
                    String strs[] = str.split(";");
                    if (strs[0].equals(fields[i].getName())) {
    
    
                        fields[i].set(object, strs[1].equals("备注") || strs[1].equals("其他") ? "" : strs[1]);
                        break;
                    }
                }
            }
            return object;
        } catch (IllegalAccessException e) {
    
    
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (InstantiationException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

}

应用

// lableCodeList 拼接好的集合,为{"name+value","name1+value1"}格式
Vo vo = new Vo();
Vo newVo = (Vo) SetClassUtil.setClassFileValue(vo.getClass(), lableCodeList);

猜你喜欢

转载自blog.csdn.net/weixin_44974020/article/details/116258450
今日推荐