如何通过反射获取对象中的字段?

在 Java 中有一个对象(基本上是 VO) ,我不知道它的类型。
我需要得到那个对象中不为空的值。

这怎么可能呢?

136375 次浏览

可以使用 Class#getDeclaredFields()获取类的所有声明字段。

简而言之:

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);
}
}

要了解有关反射的更多信息,请检查 关于这个主题的 Oracle 教程

也就是说,如果 VO 是一个完整的 Javabean,那么字段不一定表示 VO 的 真的属性。您更希望确定以 getis开始的公共方法,然后调用它来获取实际属性值。

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。甚至在 java.beans包中还有一个 JavaSE 提供的内置程序。

BeanInfo beanInfo = Introspector.getBeanInfo(someObject.getClass());
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
Method getter = property.getReadMethod();
if (getter != null) {
Object value = getter.invoke(someObject);
if (value != null) {
System.out.println(property.getName() + "=" + value);
}
}
}

中有一个对象(基本上是 VO) Java 和我不知道它的类型。我需要得到的值在该对象中不为空。

也许你不需要反思——这里有一个 普通 OO 型设计可以解决你的问题:

  1. 添加一个接口 Validation,该接口公开一个方法 validate,该方法检查字段并返回适当的内容。
  2. 实现所有 VO 的接口和方法。
  3. 当您得到一个 VO,即使它的 混凝土类型是未知的,您可以类型转换为 Validation,并检查它很容易。

我猜您需要空字段来以通用方式显示错误消息,因此这应该足够了。如果因为某些原因,这个对你不起作用,告诉我一声。

这里有一个快速、简单的方法,它以通用的方式完成您想要的任务。您需要添加异常处理,并且可能需要在弱散列映射中缓存 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;
}

参见下面的参考文献: