我现在的需求是,写一个方法,参数传入任意对象类型,返回这个对象的属性名称和属性值的map

解决方案 »

  1.   

    对象需要具备get方法public static Map<String, String> getObjectMap(Object o) { Map<String, String> map = null;
    if (o == null)
    return null; try { map = new HashMap<String, String>(); BeanInfo bInfo = Introspector.getBeanInfo(o.getClass());
    PropertyDescriptor propertyDescriptorp[] = bInfo.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptorp.length; i++) {
    PropertyDescriptor propertyDescriptor = propertyDescriptorp[i];
    if (!"class".equalsIgnoreCase(propertyDescriptor.getName().trim())) {
    Method m = propertyDescriptor.getReadMethod();
    Object result = m.invoke(o);
    if (result == null)
    result = "null";
    map.put(propertyDescriptor.getName(), result.toString());
    }
    } } catch (IntrospectionException e) {
    e.printStackTrace();
    } catch (IllegalArgumentException e) {
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    e.printStackTrace();
    } return map;
    }
      

  2.   


    package com.study.reflect;import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;public class CommonManager { /**
     * @param object
     * @return
     */
    public static Map getObjectAllArgs(Object object) throws Exception{

    //获取对象的class对象
    Class<?> classType = object.getClass();

    //获取对象的所有申明过的field
    Field[] fields = classType.getDeclaredFields();

    Map map = new HashMap();

    //拼接所有field
    for(Field field : fields){
    //属性名字
    String name = field.getName();
    String first = name.substring(0, 1);

    String getMethodName = "get" + first.toUpperCase() + first.substring(1);

    Method method = classType.getDeclaredMethod(getMethodName, new Class[]{});

    Object value = method.invoke(object, new Object[]{});

    map.put(field.getName(), value);
    }

    return map;
    }
    }对象要有get方法,且get方法满足getXxx()
      

  3.   

    String getMethodName = "get" + first.toUpperCase() + first.substring(1);
    改为
    String getMethodName = "get" + first.toUpperCase() + name.substring(1);
      

  4.   


    也简单啊 instanceof 下对象 然后递归
      

  5.   

    这个也太简单了吧,我建议用Introspector,然后得到BeanInfo再得到BeanDescriptor就OK了,查查api