java的动态地创建实例变量的对象数组 [英] Java dynamically create object array of instance variables

查看:78
本文介绍了java的动态地创建实例变量的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个的POJO的实例变量需要转换为对象数组。我试图找到一种方法,这可以动态而不是处理在每个POJO添加toObjectArray()方法。

I have several pojos whose instance variables need to be converted to Object arrays. I am trying to find a way that this can be handled dynamically instead of adding a toObjectArray() method in each pojo.

下面是我想摆脱的toObjectArray()方法的示例类:

Here is a sample class with the toObjectArray() method that I would like to get rid of:

public class Contact {

  private String lastName;
  private String firstName;

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public Object[] toObjectArray() {
    return new Object[] {
      this.getLastName(),
      this.getFirstName(),
    };
  }

}

的实例变量不必为了被返回。我有一个自定义的注释,让我以反映对象数组正确的顺序。我只是想知道,如果它是可以动态地遍历一个对象的实例变量和值,以创建一个对象数组。

The instance variables do not have to be returned in order. I have a custom annotation which allows me to reflect proper order for the object array. I'm simply wondering if it is possible to dynamically iterate the instance variables and values of an object in order to create an object array.

这样的事情...

public static Object[] toObjectArray(Object obj) {
  /// cast Object to ?
  /// iterate instance variables of Contact
  /// create and return Object[]
}

public static void main(String[] args) {
  Contact contact = new Contact();
  contact.setLastName("Garcia");
  contact.setFirstName("Jerry");

  Object[] obj = toObjectArray(contact);
}

任何帮助将大大AP preciated。请让我知道,如果我需要更加清晰。

Any help would be greatly appreciated. Please let me know if I need to be more clear.

感谢您!

推荐答案

一个可行的方法,可以使用反射。

One possible way could be using reflection.

static <T> Object[] getFieldValues(final Class<T> type, final T instance) {

    final Field[] fields = type.getDeclaredFields(); // includes private fields

    final Object[] values = new Object[fields.length];

    for (int i = 0; i < fields.length; i++) {
        if (!fields[i].isAccessible()) {
            fields[i].setAccessible(true); // enables private field accessing.
        }
        try {
            values[i] = fields[i].get(instance);
        } catch (IllegalAccessException iae) {
            // @@?
        }
    }

    return values;
}

这篇关于java的动态地创建实例变量的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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