Java Reflection Field Set setField(Class clazz, Object instance, String field, Object value)

Here you can find the source of setField(Class clazz, Object instance, String field, Object value)

Description

set Field

License

Open Source License

Declaration

public static void setField(Class<?> clazz, Object instance, String field, Object value)
            throws NoSuchFieldException, IllegalAccessException 

Method Source Code


//package com.java2s;
/*//from w w  w . j  a v  a  2  s.  co m
 * BungeeTabListPlus - a BungeeCord plugin to customize the tablist
 *
 * Copyright (C) 2014 - 2015 Florian Stober
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.Field;

public class Main {
    public static void setField(Class<?> clazz, Object instance, String field, Object value)
            throws NoSuchFieldException, IllegalAccessException {
        Field f = clazz.getDeclaredField(field);
        f.setAccessible(true);
        f.set(instance, value);
    }

    public static void setField(Class<?> clazz, Object instance, String field, Object value, int tries)
            throws NoSuchFieldException, IllegalAccessException {
        while (--tries > 0) {
            try {
                setField(clazz, instance, field, value);
                return;
            } catch (NoSuchFieldException | IllegalAccessException ignored) {
            }
        }
        setField(clazz, instance, field, value);
    }
}

Related

  1. setField(Class type, String name, Object instance, Object value)
  2. setField(Class klazz, Object recipient, String fieldName, Object newValue)
  3. setField(Class clazz, String fieldName, T instance, Object value)
  4. setField(Class c, Object inst, String name, Object value)
  5. setField(Class cl, String name, Object obj, Object value)
  6. setField(Class clazz, Object obj, String fieldName, Object value)
  7. setField(Class ownerClass, Object owner, String fieldName, Object newValue)
  8. setField(Class target, Class fieldType, int index, Object obj, Object value)
  9. setField(Class clazz, T instance, String fieldName, Object value)