[Java] How to Map Properties from HashMap to Java Bean

On this example, im trying to do a simple mapping from java.util.Map to a simple Java Bean, using Apache Common BeanUtils.

First as usual, a simple java bean.

package com.edw.bean;

public class Student {
    public String name;
    public int age;

    public Student() {

    // other setter and getter

And this is how i map simple values to Student bean.

package com.edw.main;

import com.edw.bean.Student;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;

public class Main {
    public static void main(String[] args) throws Exception {
        Student student = new Student();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "edwin");
        map.put("age", 22);
        BeanUtils.populate(student, map);

This is the libraries that i used,

Actually, my plan is to create a dynamic bean to bean mapping configured via xml files. And this class is my starting point. (H)




about 4 years ago

om, bedanya sama bean biasa yang menggunakan setter getter lebih mudah mana jika di apliaksikan ke dalam database yang menggunakan format xml dsb, yang mana di dalamnya ada class bean tersebut.? thx before



about 4 years ago

pertanyaan loe muter-muter zis wkkwkw....

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked

:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)