java 使用 BeanUtils 检索字段值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6122432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve field values using BeanUtils
提问by TheLameProgrammer
I want to extract private field values that are not marked by certain custom annotation, is this possible via BeanUtils? If yes, how?
我想提取未由某些自定义注释标记的私有字段值,这可以通过 BeanUtils 实现吗?如果是,如何?
回答by MarcoS
Yes, assuming that you know the fields names. You can use PropertyUtils.getSimpleProperty(...)
. See also herefor an example.
是的,假设您知道字段名称。您可以使用PropertyUtils.getSimpleProperty(...)
. 另请参见此处的示例。
回答by Stephan
No, it is not possible with BeanUtils. But you can use Java's own reflection tools like this:
不,使用 BeanUtils 是不可能的。但是您可以像这样使用 Java 自己的反射工具:
public class BeanUtilTest {
public static void main(String[] args) throws ... {
MyBean bean = new MyBean();
Field field = bean.getClass().getDeclaredField("bar");
field.setAccessible(true);
System.out.println(field.get(bean));
}
public static class MyBean {
private final String bar = "foo";
}
}
Please consider: Accessing private fields with reflection is very bad style and should be done only for tests or if you are sure there is no other way. If you don't have the ability to change the sources of the class you're trying to access, it might be a last resort. But consider that the behavior might change in the future (e.g. as an update of the library you're using) and break your code.
请考虑:使用反射访问私有字段是非常糟糕的风格,应该仅用于测试或如果您确定没有其他方法。如果您无法更改您尝试访问的类的来源,那么这可能是最后的手段。但考虑到行为在未来可能会发生变化(例如,作为您正在使用的库的更新)并破坏您的代码。
Edit:If BeanUtils or PropertyUtils are working, this means there is a public getter for this property and you should be using it instead of using reflection. Using PropertyUtils on a private field without a public getter throws a NoSuchMethodException.
编辑:如果 BeanUtils 或 PropertyUtils 正在工作,这意味着此属性有一个公共 getter,您应该使用它而不是使用反射。在没有公共 getter 的私有字段上使用 PropertyUtils 会引发 NoSuchMethodException。