반응형

참고: http://www.leveluplunch.com/java/examples/convert-object-bean-properties-map-key-value/

 

Bean 데이터를 공통으로 받아서 Map 형태로 사용하고 싶을 때 유용하게 쓸 수 있다.

 

- 생 자바로

public void convert_object_to_map_java() throws IntrospectionException,
        IllegalAccessException, IllegalArgumentException,
        InvocationTargetException {

    NoteBook actionMethodNoteBook = new NoteBook(100, "Action Method Notebook");

    Map<String, Object> objectAsMap = new HashMap<String, Object>();
    BeanInfo info = Introspector.getBeanInfo(actionMethodNoteBook.getClass());
    for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
        Method reader = pd.getReadMethod();
        if (reader != null)
            objectAsMap.put(pd.getName(),reader.invoke(actionMethodNoteBook));
    }

    assertThat(objectAsMap, hasEntry("numberOfSheets", (Object) new Double(100.0)));
    assertThat(objectAsMap, hasEntry("description", (Object) "Action Method Notebook"));
}

 

 

 

- 잭슨 형식

public void convert_object_to_map_jackson () {
   
    NoteBook moleskineNoteBook = new NoteBook(200, "Moleskine Notebooks");
   
    ObjectMapper objectMapper = new ObjectMapper();
   
    @SuppressWarnings("unchecked")
    Map<String, Object> objectAsMap = objectMapper.convertValue(moleskineNoteBook, Map.class);
   
    assertThat(objectAsMap, hasEntry("numberOfSheets", (Object) new Double(200.0)));
    assertThat(objectAsMap, hasEntry("description", (Object) "Moleskine Notebooks"));
}

 

 

 

- Apach Common 이용

public void convert_object_to_map_apache_commons () throws IllegalAccessException,
    InvocationTargetException, NoSuchMethodException {
   
    NoteBook fieldNoteBook = new NoteBook(878, "Field Notebook");

    @SuppressWarnings("unchecked")
    Map<String, Object> objectAsMap = BeanUtils.describe(fieldNoteBook);
   
    assertThat(objectAsMap, hasEntry("numberOfSheets", (Object) "878.0"));
    assertThat(objectAsMap, hasEntry("description", (Object)  "Field Notebook"));
}

반응형

WRITTEN BY
데르벨준

,