copy All Fields from class to target - Android java.lang.reflect

Android examples for java.lang.reflect:Field

Description

copy All Fields from class to target

Demo Code


//package com.java2s;

import java.lang.reflect.Field;

public class Main {
    public static boolean copyAllFields(Class<?> clsBase, Object src,
            Object target) {//from  ww  w.j  av a2s .  c o  m
        if (src == null || target == null) {
            return false;
        }

        Class<?> clsType = clsBase;
        while (clsType != null) {
            Field[] fields = clsType.getDeclaredFields();
            for (Field fid : fields) {
                try {
                    fid.setAccessible(true);
                    Object ref = fid.get(src);
                    fid.set(target, ref);
                } catch (Exception e) {
                    // Debug.logD("setField error: " + fid.getName() + " @ " + clsType.getSimpleName());
                    // e.printStackTrace();
                }
            }
            clsType = clsType.getSuperclass();
        }

        return true;
    }
}

Related Tutorials