set Field Value - Java Reflection

Java examples for Reflection:Field Value

Description

set Field Value

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        Object bean = "java2s.com";
        String fieldName = "java2s.com";
        Object value = "java2s.com";
        setFieldValue(bean, fieldName, value);
    }/*from   ww w.  ja va2s  . co m*/

    public static void setFieldValue(Object bean, String fieldName,
            Object value) {
        try {
            Field field = bean.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(bean, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials