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

Swa*_*pna 65 java reflection

我在Java中有一个对象(基本上是一个VO),我不知道它的类型.
我需要获取该对象中不为null的值.

如何才能做到这一点?

Bal*_*usC 124

您可以使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

要了解有关反射的更多信息,请查看有关该主题Sun教程.


也就是说,字段不一定代表VO的属性.您更愿意确定以get或开头的公共方法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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

反过来说,可能有更优雅的方法来解决您的实际问题.如果您详细说明您认为这是正确解决方案的功能要求,那么我们可以建议正确的解决方案.有许多工具可用于按摩javabeans.


Sea*_*oyd 12

这是一种快速而肮脏的方法,可以通用方式执行您想要的操作.您需要添加异常处理,并且您可能希望将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;
}
Run Code Online (Sandbox Code Playgroud)

见这些参考文献: