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

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

问题描述

我在Java中有一个对象(基本上是一个VO),我不知道它的类型。

我需要获取该对象中不为null的值。

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.

如何做到这一点?

推荐答案

你可以用< a href =http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getDeclaredFields%28%29 =noreferrer> Class# getDeclaredFields() 获取该类的所有声明字段。你可以使用 字段#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的属性。您更愿意确定以 get 开头的公共方法,然后调用它来获取真实的属性值。

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






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


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天全站免登陆