【发布时间】:2010-06-07 12:45:24
【问题描述】:
我在 Java 中有一个对象(基本上是 VO),但我不知道它的类型。
我需要获取该对象中不为空的值。
如何做到这一点?
【问题讨论】:
标签: java reflection
我在 Java 中有一个对象(基本上是 VO),但我不知道它的类型。
我需要获取该对象中不为空的值。
如何做到这一点?
【问题讨论】:
标签: java reflection
您可以使用Class#getDeclaredFields() 来获取该类的所有声明字段。您可以使用Field#get() 来获取值。
简而言之:
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);
}
}
要了解有关反射的更多信息,请查看Sun tutorial on the subject。
也就是说,字段不一定全部代表 VO 的属性。您希望确定以 get 或 is 开头的公共方法,然后调用它来获取 real 属性值。
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);
}
}
}
反过来说,可能有更优雅的方法来解决您的实际问题。如果您详细说明您认为这是正确解决方案的功能需求,那么我们可能会提出正确的解决方案。有很多,很多工具可以用来按摩javabean。
【讨论】:
这是一种快速而肮脏的方法,可以以通用方式完成您想要的操作。您需要添加异常处理,并且您可能希望将 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;
}
请参阅以下参考资料:
【讨论】:
我有一个对象(基本上是一个 VO) Java,我不知道它的类型。我需要获取该对象中不为空的值。
也许您不需要对此进行反思 - 这是一个可能解决您的问题的简单的 OO 设计:
Validation,它公开一个方法validate,该方法检查字段并返回适当的内容。 Validation 并轻松检查。我想您需要为空的字段以通用方式显示错误消息,这样就足够了。如果由于某种原因这对您不起作用,请告诉我。
【讨论】: