set Java Bean Property Values - Java Reflection

Java examples for Reflection:Java Bean

Description

set Java Bean Property Values

Demo Code


//package com.java2s;
import java.lang.reflect.Field;

public class Main {

    public static void setValues(String[] fields, Object bean,
            Object[] values) {//  w ww. j  a  va  2  s . c om
        for (int i = 0; i < fields.length; i++) {
            setValue(fields[i], bean, values[i]);
        }
    }

    public static void setValue(String field, Object bean, Object value) {
        try {
            Field f = bean.getClass().getDeclaredField(field);
            boolean b = f.isAccessible();
            f.setAccessible(true);
            f.set(bean, value);
            f.setAccessible(b);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials