如何通过反射获取对象中的字段? [英] How to get the fields in an Object via reflection?

查看:31
本文介绍了如何通过反射获取对象中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an object (basically a VO) in Java and I don't know its type.
I need to get values which are not null in that object.

如何做到这一点?

推荐答案

您可以使用 Class#getDeclaredFields() 获取类的所有声明字段.您可以使用 Field#get() 获取值.

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

简而言之:

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

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

To learn more about reflection, check the Sun tutorial on the subject.

也就是说,字段不一定全部代表 VO 的属性.您更愿意确定以 getis 开头的公共方法,然后调用它来获取 real 属性值.

That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

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.


That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.

这篇关于如何通过反射获取对象中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆