开发者

In java i have a bean object(type unknown) i want to put the members of it into one hashmap

开发者 https://www.devze.com 2023-03-01 04:37 出处:网络
In java i have a bean object(type unknown) i want to put the values of members of that bean into one HashMap with class members as key.Without using reflection can i do that if so how ? otherwise tell

In java i have a bean object(type unknown) i want to put the values of members of that bean into one HashMap with class members as key.Without using reflection can i do that if so how ? otherwise tell me a good way to do it using reflection beanObject = { name="raja",age="20"} to haspMapObj = {name="raja",age="20"}

As peoples you said i tried introspector: thank you for your answer and advise friends.

     Class myClass =myObj.getClass();
     info = Introspector.getBeanInfo(myClass);
     for ( PropertyDescriptor pd : info.getPropertyDescriptors() ){
       String name = pd.getName();
       System.out.println("*************开发者_运维问答"+name+","+ pd.getValue(name));
     }

but the above is print only the name the value's is coming as null. bcoz we are passing only the class type not the object reference. how do we do to get the value?


You can use the Introspector to get all the fields of a bean and their values. (This wraps reflection)


I think you can't do it without reflection. With reflection you can do something like this:

    Map<String, Field> map = new HashMap<String, Field>();
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        map.put(field.getName(), field);
    }


I do not see any possibility without using reflection at least indirectly via frameworks.

If you take a look at the Apache Commons Beanutils you might find some helpful methods:

http://commons.apache.org/beanutils/

More specified:

http://commons.apache.org/beanutils/v1.8.3/apidocs/org/apache/commons/beanutils/BeanMap.html

Best regards!


You can use introspection, which is based on reflection: http://download.oracle.com/javase/6/docs/api/java/beans/Introspector.html

But what exactly do want to do in the end? Maybe there is a better way...

To get the value from a PropertyDescriptor pd:

Object value = pd.getReadMethod().invoke(myObj, new Object[]{});

Note, some time ago I wrote a utility class, which you might find useful:

http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/beans/BeanIntrospector.html

0

精彩评论

暂无评论...
验证码 换一张
取 消