Java Reflection Field Set setField(Class ownerClass, Object owner, String fieldName, Object newValue)

Here you can find the source of setField(Class ownerClass, Object owner, String fieldName, Object newValue)

Description

set Field

License

Open Source License

Declaration

static void setField(Class<?> ownerClass, Object owner, String fieldName, Object newValue) 

Method Source Code


//package com.java2s;
/*// w ww .ja  v  a  2 s.com
 * Copyright (c) 2006-2011 Rog?rio Liesenfeld
 * This file is subject to the terms of the MIT license (see LICENSE.txt).
 */

import java.lang.reflect.*;

public class Main {
    static void setField(Object owner, String fieldName, Object newValue) {
        setField(owner.getClass(), owner, fieldName, newValue);
    }

    static void setField(Class<?> ownerClass, Object owner, String fieldName, Object newValue) {
        Field f;

        try {
            f = ownerClass.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }

        f.setAccessible(true);

        try {
            //noinspection unchecked
            f.set(owner, newValue);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. setField(Class clazz, String fieldName, T instance, Object value)
  2. setField(Class c, Object inst, String name, Object value)
  3. setField(Class cl, String name, Object obj, Object value)
  4. setField(Class clazz, Object instance, String field, Object value)
  5. setField(Class clazz, Object obj, String fieldName, Object value)
  6. setField(Class target, Class fieldType, int index, Object obj, Object value)
  7. setField(Class clazz, T instance, String fieldName, Object value)
  8. setField(Class clazz, T instance, String fieldName, Object value)
  9. setField(Field f, Object instance, Object value)