copy Bean To Beans - Java Reflection

Java examples for Reflection:Java Bean

Description

copy Bean To Beans

Demo Code


//package com.java2s;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {

    public static void copyBeanToBeans(List bean, Object beans) {

        try {// www  . j av  a2s  .c o  m
            if (bean != null) {
                Field[] field = beans.getClass().getDeclaredFields();
                String claname[] = new String[field.length];
                //System.out.println(field.length);
                for (int i = 0; i < field.length; i++) {
                    try {
                        List list = new ArrayList();
                        String fieldname = field[i].getName();
                        String setMethodname = new StringBuffer("set")
                                .append(fieldname.substring(0, 1)
                                        .toUpperCase())
                                .append(fieldname.substring(1)).toString();
                        String getMethodname = new StringBuffer("get")
                                .append(fieldname.substring(0, 1)
                                        .toUpperCase())
                                .append(fieldname.substring(1)).toString();
                        int k = 0;
                        Iterator enmu = bean.iterator();
                        while (enmu.hasNext()) {
                            Object temp = enmu.next();

                            claname[i] = temp.getClass()
                                    .getDeclaredField(fieldname).getType()
                                    .getName();
                            Method method = temp.getClass().getMethod(
                                    getMethodname, null);
                            list.add(method.invoke(temp, null));

                            k++;
                        }
                        Class[] cla = new Class[1];
                        cla[0] = beans.getClass()
                                .getDeclaredField(fieldname).getType();
                        //System.out.println(cla[0]);
                        Object[] paras = new Object[1];
                        Object obj = null;
                        obj = Array.newInstance(Class.forName(claname[i]),
                                bean.size());
                        list.toArray((Object[]) obj);
                        paras[0] = obj;
                        beans.getClass().getMethod(setMethodname, cla)
                                .invoke(beans, paras);
                    } catch (Exception ex) {
                        //?beans?List?
                    }
                }
            }

        } catch (Exception e) {
            //            log.error("ListBeans", e);
        }
    }
}

Related Tutorials