【问题标题】:Find a PropertyDescriptor recursively using Reflection in Java在 Java 中使用反射递归查找 PropertyDescriptor
【发布时间】:2012-10-17 18:34:47
【问题描述】:

有没有办法使用 Java 反射递归地找到属性描述符?

想象一个场景,其中 User 类有一个名为 profile 的字段,它本身是另一个具有 email 属性的类。

通过拥有用户对象,我需要能够访问 profile.email,因此理想的方法签名应该类似于以下内容:

public PropertyDescriptor findPropertyDescriptor(Class<?> clazz, String path)
{
    // Code!
}

调用会是这样的:

findPropertyDescriptor(User.class, "profile.email")

我也认为像下面这样的调用也应该是可能的:

findPropertyDescriptor(User.class, "addresses[2].postCode")

【问题讨论】:

    标签: java reflection introspection


    【解决方案1】:

    由于没有人提出解决方案,我必须在这里回答我的问题。

    感谢 Spring,这已经实现:

    public static <T> PropertyDescriptor getPropertyDescriptor(T rootObject, String path)
    {
        BeanWrapperImpl wrapper = new BeanWrapperImpl(rootObject);
        return wrapper.getPropertyDescriptor(path);
    }
    

    除了问题中提到的要求外,它还支持地图。

    【讨论】:

    • 我找不到这个确切的方法(带路径)。你能指出我正确的方向吗?
    • 严格来说,您并没有解决自己的问题,因为您使用的不是 Class 对象而是一个实例。
    猜你喜欢
    • 2017-01-19
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    相关资源
    最近更新 更多