set Static Field - Java Reflection

Java examples for Reflection:Field Set

Description

set Static Field

Demo Code


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

import java.util.HashMap;

public class Main {
    private static HashMap<String, Field> sFieldCache = new HashMap<String, Field>();

    public static void setStaticField(Class<?> clazz, String fieldName,
            Object value) {/*from w w w.  j  a va2s  . c o  m*/
        try {
            Field field = getField(clazz, fieldName);
            field.set(clazz, value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    private static Field getField(Class<?> clazz, String fieldName)
            throws Throwable {
        String fieldFullName = genFieldFullName(clazz, fieldName);
        if (sFieldCache.containsKey(fieldFullName))
            return sFieldCache.get(fieldFullName);
        Field field = null;
        try {
            field = clazz.getField(fieldName);
        } catch (NoSuchFieldException e) {
        }
        if (field == null) {
            try {
                field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
            } catch (NoSuchFieldException e) {
            }
        }
        if (field == null) {
            for (clazz = clazz.getSuperclass(); clazz != Object.class; clazz = clazz
                    .getSuperclass()) {
                try {
                    field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                } catch (NoSuchFieldException e) {
                }
            }
        }
        if (field == null) {
            String msg = "";
            msg = "Can't get Field from Class " + clazz.getSimpleName()
                    + ":" + fieldName;
            throw new Throwable(msg);
        }
        sFieldCache.put(fieldFullName, field);
        return field;
    }

    private static String genFieldFullName(Class<?> clazz, String fieldName) {
        StringBuilder name = new StringBuilder();
        name.append(clazz.getName());
        name.append(":");
        name.append(fieldName);
        return name.toString();
    }
}

Related Tutorials