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

新手上路,请多包涵

我在 Java 中有一个对象(基本上是一个 VO),但我不知道它的类型。

我需要获取该对象中不为空的值。

如何才能做到这一点?

原文由 Swapna 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 511
2 个回答

您可以使用 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);
    }
}

要了解有关反射的更多信息,请查看 有关该主题的 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 SE 甚至在 java.beans 包中提供了一个内置的。

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

原文由 BalusC 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是一种快速而肮脏的方法,可以以通用方式执行您想要的操作。您需要添加异常处理,并且您可能希望将 BeanInfo 类型缓存在 weakhashmap 中。

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

请参阅这些参考资料:

原文由 Sean Patrick Floyd 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题