Java中的内省库

时间:2012-02-11 00:45:53

标签: java spring

Java中是否有一个内省类可以获取类的字段,方法和注释,包括来自超类缓存的结果?

修改 像spring,hibernate,jackson这样的每个主要框架都会做一些深刻的反省,我很想知道这些库中是否有可以使用的东西。

3 个答案:

答案 0 :(得分:6)

我在Spring BeanWrapper中找到了我想要的东西:

final BeanWrapper sourceBean = new BeanWrapperImpl(MyType.class);
final PropertyDescriptor[] propertyDescriptors = sourceBean.getPropertyDescriptors();
for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
   logger.info(propertyDescriptor.getName() + ":" + propertyDescriptor.getPropertyType());
}

使用BeanWrapper,您可以访问所有字段,setter和getter,注释。每个类都被缓存。

答案 1 :(得分:2)

您可能也对Commons BeanUtils感兴趣。它提供了一组很好的帮助程序,可以轻松地进行自省(主要是Java bean属性)。

答案 2 :(得分:1)

Spring框架的BeanWrapper在版本3之后有了很大的改进,这是事实。但是如果你想要一个更高性能的BeanWrapper,你可能想要考虑juffrou-reflect的BeanWrapper - 它在实例化方面更具性能,在设置和获取值和类型方面更具性能。而且它也比Spring更灵活。

我当然有偏见,因为我开发了Juffrou - 反映自己,但我认为你可以从我的BeanWrapper中获得更多。当spring的BeanWrapper在2.x版本中时,我开始开发它,从那时起我就没有放过。它也是开源的,因此您可以完全免费使用和修改。

这是一个示例用例:

BeanWrapper beanWrapper = new BeanWrapper(BeanWrapperContext.create(Programmer.class)); // Programmer extends Person
beanWrapper.setValue("specialization", "Bean Wrappers :)"); // set value to Programmer's property
beanWrapper.setValue("firstName", "Carlos"); // set value to Person's property
beanWrapper.setValue("home.town", "Lisboa");        // set value to a nested bean's property
for(String propertyName : beanWrapper.getPropertyNames()) {
    Type type = beanWrapper.getType(propertyName);
    Object value = beanWrapper.getValue(propertyName);
    Logger.debug(type + ": " + value);
}
Programmer programmer = (Programmer) beanWrapper.getBean();  // get the wrapped object
BeanWrapperContext context = beanWrapper.getContext(); // Reuse the context and save on introspection overhead

您可以在http://juffrou.sourceforge.net查看。还有一个全面的PDF手册和javadocs,因此您可以从一开始就充分利用它的全部潜力。但如果你对它的使用有任何疑问,我会非常乐意回应。

干杯

卡洛斯