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

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

Description

set Field

License

Apache License

Declaration

public static <T> void setField(final Object instance, final String fieldName, final T value) 

Method Source Code

//package com.java2s;
/*/* w w w  .ja  v  a  2 s  .c  om*/
 * Copyright 2013-2015 Eris IT AB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.lang.reflect.Field;

public class Main {
    public static <T> void setField(final Object instance, final String fieldName, final T value) {
        Class<?> instanceClass = instance.getClass();
        Field field = getDeclaredField(instanceClass, fieldName);
        while (field == null) {
            instanceClass = instanceClass.getSuperclass();
            field = getDeclaredField(instanceClass, fieldName);
        }
        field.setAccessible(true);
        try {
            field.set(instance, value);
        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);
        } finally {
            field.setAccessible(false);
        }
    }

    private static Field getDeclaredField(final Class<?> instanceClass, final String fieldName) {
        if (instanceClass == null) {
            throw new RuntimeException(new NoSuchFieldException(fieldName));
        }
        try {
            return instanceClass.getDeclaredField(fieldName);
        } catch (final NoSuchFieldException | SecurityException e) {
            return null;
        }
    }
}

Related

  1. setField(Field field, T newValue, Object instance)
  2. setField(Field field, U instance, Object value)
  3. setField(final Field field, final Object instance, final Object value)
  4. setField(final Field field, final Object object, final Object value)
  5. setField(final O object, final String fieldName, final V value)
  6. setField(final Object obj, final String fieldName, final int value)
  7. setField(final Object obj, final String fieldName, final Object value)
  8. setField(final Object obj, final String name, final Object value)
  9. setField(final Object obj, final String variableName, final Object variableValue)