set Private Static Final Field - Java Reflection

Java examples for Reflection:Field Set

Description

set Private Static Final Field

Demo Code


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

public class Main {
    public static boolean setPrivateStaticFinalField(Class clazz,
            String fieldName, Object value) {
        return setPrivateFinalField(clazz, fieldName, null, value);
    }/*  w  w  w  .j a v a  2  s  .  com*/

    public static boolean setPrivateFinalField(Class clazz,
            String fieldName, Object instance, Object value) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);

            Field modifiersField = Field.class
                    .getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(field, field.getModifiers()
                    & ~Modifier.FINAL);

            field.set(instance, value);
            return true;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
}

Related Tutorials