简体   繁体   English

将Java类中的成员变量转换为对象数组,反之亦然

[英]converting member variables in a Java class to an object array and vice versa

Have a class including 30+ member variables, need to pass it to a function and then return it from the function after processing. 有一个包含30多个成员变量的类,需要将其传递给函数,然后在处理后从函数返回它。 but this function only accept fundamental data types, such as string, int. 但是此函数仅接受基本数据类型,例如string,int。 I want to convert these member variables into an object array, pass it to the function, then convert back. 我想将这些成员变量转换为对象数组,将其传递给函数,然后再转换回去。

have a easy way to do these except converting one bye one? 有一个简单的方法来完成这些任务,除了转换一个再见?

source code like this: 像这样的源代码:

class A{
    int member1;
    string member2;
    int member3;
    //other member variables

    A(){
        //source code
    }

    A(Object[] objs){
        //assign objects in "objs" array to member variables
    }

    Object[] asArray(){
        //put member variables into a object array
    }
 };

 class B extends SuperB{
     //can't modify SuperB, only can inherit it
     //only accept fundamental data types, such as string, int
     public Object[] run(Object... args){
         A a = new A(args);

         //processing

         return a.asArray();
     } 
 }

 public static void main(String[] args){
     A a = new A();

     //other source code

     Processor p = new Processor();
     object[] updatedObjs = b.call("B", a.asArray());
     a = new A(updatedObjs);

     //other source code
 };

To do what you are asking you need to do a little bit of java reflection. 要执行您要求的操作,您需要做一点Java反射。 Loop through all the fields and add them to an array. 遍历所有字段并将它们添加到数组中。

If you are not sure what is java reflection: 如果您不确定什么是Java反射:

http://docs.oracle.com/javase/tutorial/reflect/ http://docs.oracle.com/javase/tutorial/reflect/

Otherwise, if you dont want to go through spinning out something on your own, you could use the immensely powerful and popular common beanutils 否则,如果您不想自己动手制作某些东西,则可以使用功能强大且流行的通用beanutils

http://commons.apache.org/proper/commons-beanutils/ http://commons.apache.org/proper/commons-beanutils/

If you use the dynabean feature, you could do all this in a few lines of code: 如果使用dynabean功能,则可以通过几行代码来完成所有这些操作:

WrapDynaBean wrapDynaBean=new WrapDynaBean(new A());
DynaProperty[] dynaProperties = wrapDynaBean.getDynaClass().getDynaProperties();
List<Object> objects=new ArrayList<>();
for (DynaProperty dynaProperty : dynaProperties) {
    System.out.println(dynaProperty.getName()+" = "+wrapDynaBean.get(dynaProperty.getName()));
    objects.add(wrapDynaBean.get(dynaProperty.getName()));
}
Object[] theArrayYouWant=objects.toArray(new Object[objects.size()]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM