Java 如何通过反射获取对象中的字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2989560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the fields in an Object via reflection?
提问by Swapna
I have an object (basically a VO) in Java and I don't know its type.
I need to get values which are not null in that object.
我在 Java 中有一个对象(基本上是一个 VO),但我不知道它的类型。
我需要获取该对象中不为空的值。
How can this be done?
如何才能做到这一点?
采纳答案by BalusC
You can use Class#getDeclaredFields()
to get all declared fields of the class. You can use Field#get()
to get the value.
您可以使用Class#getDeclaredFields()
来获取类的所有声明字段。您可以使用Field#get()
来获取值。
In short:
简而言之:
Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
field.setAccessible(true); // You might want to set modifier to public first.
Object value = field.get(someObject);
if (value != null) {
System.out.println(field.getName() + "=" + value);
}
}
To learn more about reflection, check the Sun tutorial on the subject.
That said, the fields does not necessarily allrepresent properties of a VO. You would rather like to determine the public methods starting with get
or is
and then invoke it to grab the realproperty values.
也就是说,这些字段不一定都代表 VO 的属性。您更愿意确定以get
or开头的公共方法is
,然后调用它来获取实际属性值。
for (Method method : someObject.getClass().getDeclaredMethods()) {
if (Modifier.isPublic(method.getModifiers())
&& method.getParameterTypes().length == 0
&& method.getReturnType() != void.class
&& (method.getName().startsWith("get") || method.getName().startsWith("is"))
) {
Object value = method.invoke(someObject);
if (value != null) {
System.out.println(method.getName() + "=" + value);
}
}
}
That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, manytools available to massage javabeans.
反过来说,可能有更优雅的方法来解决您的实际问题。如果您更详细地说明您认为这是正确解决方案的功能需求,那么我们可能会建议正确的解决方案。有许多工具可用于按摩 javabean。
回答by ewernli
I've an object (basically a VO) in Java and I don't know its type. I need to get values which are not null in that object.
我在 Java 中有一个对象(基本上是一个 VO),但我不知道它的类型。我需要获取该对象中不为空的值。
Maybe you don't necessary need reflection for that -- here is a plain OO designthat might solve your problem:
也许您不需要为此进行反射——这是一个简单的 OO 设计,可以解决您的问题:
- Add an interface
Validation
which expose a methodvalidate
which checks the fields and return whatever is appropriate. - Implement the interface and the method for all VO.
- When you get a VO, even if it's concretetype is unknown, you can typecast it to
Validation
and check that easily.
- 添加一个接口
Validation
,该接口公开一个validate
检查字段并返回任何适当内容的方法。 - 为所有 VO 实现接口和方法。
- 当你得到一个 VO 时,即使它的具体类型未知,你也可以将它的类型转换为
Validation
并轻松检查。
I guess that you need the field that are null to display an error message in a generic way, so that should be enough. Let me know if this doesn't work for you for some reason.
我想您需要空字段以通用方式显示错误消息,这样就足够了。如果由于某种原因这对您不起作用,请告诉我。
回答by Sean Patrick Floyd
Here's a quick and dirty method that does what you want in a generic way. You'll need to add exception handling and you'll probably want to cache the BeanInfo types in a weakhashmap.
这是一种快速而肮脏的方法,可以以通用方式执行您想要的操作。您需要添加异常处理,并且您可能希望在弱哈希图中缓存 BeanInfo 类型。
public Map<String, Object> getNonNullProperties(final Object thingy) {
final Map<String, Object> nonNullProperties = new TreeMap<String, Object>();
try {
final BeanInfo beanInfo = Introspector.getBeanInfo(thingy
.getClass());
for (final PropertyDescriptor descriptor : beanInfo
.getPropertyDescriptors()) {
try {
final Object propertyValue = descriptor.getReadMethod()
.invoke(thingy);
if (propertyValue != null) {
nonNullProperties.put(descriptor.getName(),
propertyValue);
}
} catch (final IllegalArgumentException e) {
// handle this please
} catch (final IllegalAccessException e) {
// and this also
} catch (final InvocationTargetException e) {
// and this, too
}
}
} catch (final IntrospectionException e) {
// do something sensible here
}
return nonNullProperties;
}
See these references:
请参阅这些参考资料:
- BeanInfo(JavaDoc)
- Introspector.getBeanInfo(class)(JavaDoc)
- Introspection(Sun Java Tutorial)
- BeanInfo(JavaDoc)
- Introspector.getBeanInfo(class)(JavaDoc)
- 自省(Sun Java 教程)