Java内省:要映射的对象 [英] Java introspection: object to map
问题描述
我有一个Java对象 obj
,其属性 obj.attr1
, obj。 attr2
等。这些属性可能通过额外的间接访问: obj.getAttr1()
, obj.getAttr2 ()
,如果不公开的话。
I have a Java object obj
that has attributes obj.attr1
, obj.attr2
etc. The attributes are possibly accessed through an extra level of indirection: obj.getAttr1()
, obj.getAttr2()
, if not public.
挑战:我想要一个接受对象的函数,并返回a Map< String,Object>
,其中键是字符串attr1
, attr2
等,值是相应的对象 obj.attr1
, obj.attr2
。
我想这个函数会被调用类似
The challenge: I want a function that takes an object, and returns a Map<String, Object>
, where the keys are strings "attr1"
, "attr2"
etc. and values are the corresponding objects obj.attr1
, obj.attr2
.
I imagine the function would be invoked with something like
-
toMap(obj)
, - 或
toMap(obj,attr1,attr3)
(其中attr1
和attr3
是obj
的属性的子集), - 或者
toMap(obj,getAttr1,getAttr3)
如有必要。
toMap(obj)
,- or
toMap(obj, "attr1", "attr3")
(whereattr1
andattr3
are a subset ofobj
's attributes), - or perhaps
toMap(obj, "getAttr1", "getAttr3")
if necessary.
我对Java的内省了解不多:你是如何用Java做的?
I don't know much about Java's introspection: how do you do that in Java?
现在,对于我关心的每种对象类型,我都有一个专门的 toMap()
实现,它是太多的样板了。
Right now, I have a specialized toMap()
implementation for each object type that I care about, and it's too much boilerplate.
注意:对于那些了解Python的人,我想要像 OBJ .__字典__
。或 dict((attr,obj .__ getattribute __(attr))attr_list中的attr)
用于子集变体。
NOTE: for those who know Python, I want something like obj.__dict__
. Or dict((attr, obj.__getattribute__(attr)) for attr in attr_list)
for the subset variant.
推荐答案
您可以使用JavaBeans内省。阅读 java.beans.Introspector
类:
You can use JavaBeans introspection for this. Read up on the java.beans.Introspector
class:
public static Map<String, Object> introspect(Object obj) throws Exception {
Map<String, Object> result = new HashMap<String, Object>();
BeanInfo info = Introspector.getBeanInfo(obj.getClass());
for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
Method reader = pd.getReadMethod();
if (reader != null)
result.put(pd.getName(), reader.invoke(obj));
}
return result;
}
大警告:我的代码处理getter方法只要;它找不到裸露的田野。对于字段,请参阅高度咖啡因的答案。 :-)(您可能希望将这两种方法结合起来。)
Big caveat: My code deals with getter methods only; it will not find naked fields. For fields, see highlycaffeinated's answer. :-) (You will probably want to combine the two approaches.)
这篇关于Java内省:要映射的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!