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

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

Description

set Field

License

Open Source License

Declaration

public static void setField(final Object obj, final String fieldName, final Object value) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Field;

public class Main {
    public static void setField(final Object obj, final String fieldName, final Object value) {
        Field field = null;//  w w  w.j a v a 2s . co  m
        try {
            field = obj.getClass().getDeclaredField(fieldName);
        } catch (NoSuchFieldException ex) {
            throw new IllegalArgumentException(
                    "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
        }

        field.setAccessible(true);

        try {
            field.set(obj, value);
        } catch (IllegalAccessException ex) {
            throw new IllegalStateException(
                    "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
        }

    }
}

Related

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