在java中我有一个bean对象(类型未知)我想将它的成员放入一个散列图中
在java中,我有一个bean对象(类型未知),我想将该bean的成员值放入一个以类成员作为键的HashMap中。如果不使用反射,我可以做到这一点吗?否则告诉我一个使用反射来做到这一点的好方法 beanObject = { name="raja",age="20"} 到 haspMapObj = {name="raja",age="20"}
正如人们所说,我尝试了内省: 谢谢各位朋友的解答和指教。
Class myClass =myObj.getClass();
info = Introspector.getBeanInfo(myClass);
for ( PropertyDescriptor pd : info.getPropertyDescriptors() ){
String name = pd.getName();
System.out.println("*************"+name+","+ pd.getValue(name));
}
但上面仅打印值的名称为空。因为我们只传递类类型而不是对象引用。我们要怎么做才能得到这个值呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 Introspector 获取 bean 的所有字段以及他们的价值观。 (这包含了反射)
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:
如果不至少通过框架间接使用反射,我看不到任何可能性。
如果您查看 Apache Commons Beanutils,您可能会发现一些有用的方法:
http://commons.apache.org /beanutils/
更具体:
http://commons.apache.org/beanutils/v1.8.3/apidocs/org/apache/commons/beanutils/BeanMap.html
致以最诚挚的问候!
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!
您可以使用基于反射的内省:
http://download.oracle.com/javase/6 /docs/api/java/beans/Introspector.html
但到底想要做什么呢?也许有更好的方法...
从 PropertyDescriptor pd 获取值:
注意,前段时间我编写了一个实用程序类,您可能会发现它很有用:
http://softsmithy.sourceforge.net/lib/docs/api/org/softsmithy/lib/beans/BeanIntrospector.html
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:
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