Java Reflection Field Set setField(String fieldName, Object instance, Object value)

Here you can find the source of setField(String fieldName, Object instance, Object value)

Description

set Field

License

Open Source License

Declaration

public static boolean setField(String fieldName, Object instance, Object value) 

Method Source Code

//package com.java2s;

import java.lang.reflect.Field;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Main {
    private static final Map<String, Field> FIELD_CACHE = new ConcurrentHashMap<>();

    public static boolean setField(String fieldName, Object instance, Object value) {
        Field field = fieldFor(instance, fieldName);
        return field != null && setField(field, instance, value);
    }/*from  w ww .  java 2 s  .c  om*/

    public static boolean setField(Field field, Object instance, Object value) {
        try {
            field.setAccessible(true);
            field.set(instance, value);
            return true;
        } catch (IllegalAccessException ex) {
            return false;
        }
    }

    public static Field fieldFor(Object object, String name) {
        try {
            String id = fieldIdentifier(object.getClass(), name);

            if (FIELD_CACHE.containsKey(id)) {
                return FIELD_CACHE.get(id);
            }
            Field field = object.getClass().getDeclaredField(name);

            FIELD_CACHE.put(id, field);
            return field;
        } catch (NoSuchFieldException ignored) {
            return null;
        }
    }

    private static String fieldIdentifier(Class<?> cls, String fieldName) {
        return cls.getName() + "||" + fieldName;
    }

    private static String fieldIdentifier(Field field) {
        return field.getDeclaringClass().getName() + "||" + field.getName();
    }
}

Related

  1. setField(Object target, String name, Object value)
  2. setField(Object targetObject, String fieldName, Object value, boolean failIfError)
  3. setField(String field, Object object, Object value)
  4. setField(String field, Object value)
  5. setField(String fieldName, Object instance, Class instanceClass, Object value)
  6. setField(String name, Object target, Object value)
  7. setField(String name, Object target, Object value)
  8. setField(T object, Field field, ResourceBundle bundle)
  9. setFieldAccessible(Class clazz, String... names)