天天看點

使用反射給實體類指派

       在項目中,可能會涉及到json,Map等資料的存儲,在解析時,常用解析方法就是定義一個常量池,再對json,map進行get,set進實體類。

       核心部分就是:

PropertyDescriptor propertyDescriptor = new PropertyDescriptor(key, BeanEntity.class);
	Method writeMethod = propertyDescriptor.getWriteMethod();
	writeMethod.invoke(pojo, value);
           

       以下示例代碼為通過反射對實體進行指派,實體類使用駝峰命名規則,Json,Map的key首字母大寫對結果無影響。

//定義一個實體類
public class BeanEntity {
    private String RiskMisMatch;
    private String Suitability;


    public String getRiskMisMatch() {
        return RiskMisMatch;
    }

    public void setRiskMisMatch(String riskMisMatch) {
        RiskMisMatch = riskMisMatch;
    }

    public String getSuitability() {
        return Suitability;
    }

    public void setSuitability(String suitability) {
        Suitability = suitability;
    }
}


//解析測試
  @Test
    public void testInvoke() throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        Map<String, String> map = new HashMap<>();
        map.put("RiskMisMatch", "Y");
        map.put("Suitability", "N");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stringFiledMap", map);

        System.out.println(jsonObject);

        Map<String, String> map1 = new HashMap<>();
        map1.put("RiskMisMatch", "N");
        map1.put("Suitability", "N");

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("stringFiledMap", map1);

        System.out.println(jsonObject1);
        List list = new ArrayList();
        list.add(jsonObject1);
        list.add(jsonObject);

        List<BeanEntity> beanEntityList = new ArrayList<>();
        for (Object object : list) {
            BeanEntity beanEntity = new BeanEntity();
            beanEntityList.add(beanEntity);

            JSONObject jso = (JSONObject) JSON.toJSON(object);
            Map<String, String> mapString = (Map<String, String>) jso.get("stringFiledMap");
            for (Map.Entry<String, String> mapss : mapString.entrySet()) {
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(mapss.getKey(), BeanEntity.class);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(beanEntity, mapss.getValue());
            }
        }

        System.out.println(beanEntityList);
        for (BeanEntity beanEntity : beanEntityList) {
            System.out.println(beanEntity.getRiskMisMatch() + "" + beanEntity.getSuitability());

        }
    }