沧海一幻觉
这是一种快速而肮脏的方法,它以一种通用的方式来完成您想要的事情。您将需要添加异常处理,并且可能需要将BeanInfo类型缓存在weakhashmap中。public Map getNonNullProperties(final Object thingy) { final Map nonNullProperties = new TreeMap(); 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;}