如何遍历 Java bean 的所有属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30661593/
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
How to iterate through all properties of a Java bean
提问by Girish
Below is my bean structure. Employee.java is the parent bean. I would like to iterate through all the properties till the Zip.java and manipulate the values.
下面是我的 bean 结构。Employee.java 是父 bean。我想遍历所有属性,直到 Zip.java 并操作这些值。
I tried to iterate this using reflection, but getDeclaredFields() will give the fields of the top level object only. How to iterate over deeper objects.
我尝试使用反射来迭代它,但是 getDeclaredFields() 只会给出顶级对象的字段。如何迭代更深的对象。
Could someone let me know how to do this in java.
有人可以让我知道如何在 Java 中执行此操作吗?
Employee.java
雇员.java
private String id;
private String name;
private int age;
private Address addr;
private Contact cont;
Address.java
地址.java
private String addr1;
private String addr2;
private String city;
private Zip zip;
Contact.java
联系方式
private String phone;
private String email;
Zip.java
压缩包
private String zipCd;
private String zipExt;
回答by NimChimpsky
for (Field field : yourObject.getClass().getDeclaredFields()) {
//do stuff
}
回答by slartidan
I strongly recommend to use an existing library and to avoid reflection in this case!Use JPA or Hibernate for database uses, use JAXB or similar for JSON/XML/other serialization, etc.
我强烈建议在这种情况下使用现有的库并避免反射!将 JPA 或 Hibernate 用于数据库用途,将 JAXB 或类似的用于 JSON/XML/其他序列化等。
However, if you want to see what an example code would look like you can have a look at this:
但是,如果您想查看示例代码的样子,可以查看以下内容:
package myOwnPackage;
import java.lang.reflect.Field;
class Address {
private String addr1;
private String addr2;
private String city;
private Zip zip;
}
class Contact {
private String phone;
private String email;
}
class Employee {
private String id;
private String name;
private int age;
private Address addr;
private Contact cont;
public void setAddr(Address addr) {
this.addr = addr;
}
}
class Zip {
private String zipCd;
private String zipExt;
}
public class Main {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
Employee employee = new Employee();
employee.setAddr(new Address());
printFields("", employee);
}
private static void printFields(String prefix, Object container) throws IllegalAccessException {
Class<? extends Object> class1 = null;
Package package1 = null;
if (container != null)
class1 = container.getClass();
if (class1 != null)
package1 = class1.getPackage();
if (package1 == null || !"myOwnPackage".equals(package1.getName())) {
System.out.println(container);
return;
}
for (Field field : class1.getDeclaredFields()) {
System.out.print(prefix+field.getName()+": ");
// make private fields accessible
field.setAccessible(true);
Object value = field.get(container);
printFields(prefix+" ", value);
}
}
}
Downsides of my code:
我的代码的缺点:
- This code uses reflection, so you are limited at the depth of fields
- Inherited fields are not printed
- 此代码使用反射,因此您在景深方面受到限制
- 不打印继承的字段
回答by Thomas
You can try this below
你可以在下面试试这个
First have your POJO's in a inner class and have an arraylist for each POJO type
首先将你的 POJO 放在一个内部类中,并为每个 POJO 类型设置一个数组列表
Public class ModelPojo{
private ArrayList<Employee > employeeList;
private ArrayList<Address> employeeList;
private ArrayList<Zip> employeeList;
private ArrayList<Contact> employeeList;
class Employee {}
class Address{}
class Contact{}
class Zip{}
}
They you can alter your values below way
他们可以通过以下方式更改您的值
public class Logic {
someMethod{
ModelPojo.Employee employee ;
ArrayList<Employee > empList = new ArrayList<Employee >();
for(int i=0;i<empList .size();i++){
employee = new ModelPojo(). new Employee ();
employee .set***("");
employee .set***("");
empList .add(product);
}
}
}
Hope this help
希望这有帮助
回答by Massimo
I did this, but I know and I strongly feel that this is considered bad programming. I did it because someone forced me to, though! (The neatest solution, I think, would've been to write more code... this was the quickest).
我这样做了,但我知道并且我强烈认为这被认为是糟糕的编程。不过,我这样做是因为有人强迫我这样做!(我认为最简洁的解决方案是编写更多代码......这是最快的)。
public String getNestedDeclaredField(Object obj, String fieldName) {
if (null == fieldName) {
return null;
}
String[] fieldNames = fieldName.split("\.");
Field field = null;
Class<? extends Object> requestClass = obj.getClass();
for (String s : fieldNames) {
try
{
field = getSuperClassField(requestClass,
requestClass.getSimpleName(), s);
field.setAccessible(true);
obj = field.get(obj);
if (null == obj) {
return null;
}
requestClass = obj.getClass();
}
catch (Exception e) {
log.error("Error while retrieving field {} from {}", s,
requestClass.toString(), e);
return "";
}
}
return obj.toString();
}
public Field getSuperClassField(Class<? extends Object> clazz,
String clazzName, String fieldName) throws NoSuchFieldException {
Field field = null;
try{
field = clazz.getDeclaredField(fieldName);
}
catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
if (StringUtils.equals(clazz.getSimpleName(), "Object")) {
log.error("Field {} doesn't seem to appear in class {}",
fieldName, clazzName);
throw new NoSuchFieldException();
}
field = getSuperClassField(clazz, clazzName, fieldName);
}
catch (Exception e) {
log.error("Error while retrieving field {} from {}", fieldName,
clazz.toString(), e);
}
return field;
}
Where fieldName is (for zipCd): addr.zip.zipCd
其中 fieldName 是(对于 zipCd):addr.zip.zipCd
It will retrieve the String value of zipCd from an Employee object.
它将从 Employee 对象中检索 zipCd 的 String 值。
回答by Razib
You may use java reflection like this -
您可以像这样使用 java 反射 -
for (Field f : Employee.class.getClass().getDeclaredFields()) {
}