translate Java Bean to Map - Java Reflection

Java examples for Reflection:Java Bean

Description

translate Java Bean to Map

Demo Code


//package com.java2s;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object obj = "java2s.com";
        System.out.println(transBean2Map(obj));
    }//from w ww  .  j  a v  a2s .c  o m

    public static Map<String, Object> transBean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo
                    .getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // ??class??
                if (!key.equals("class")) {
                    // ??property???getter??
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    map.put(key, value);
                }

            }
        } catch (Exception e) {
            System.out.println("transBean2Map Error " + e);
        }
        return map;
    }
}

Related Tutorials