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

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

Description

set Field

License

Apache License

Declaration

public static void setField(Object obj, String fieldName, Object val) throws Exception 

Method Source Code


//package com.java2s;
/*/*w ww .j  av  a 2  s  .com*/
 * Copyright 2012 Evgeny Dolganov (evgenij.dolganov@gmail.com).
 *
 * 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 void setField(Object obj, String fieldName, Object val) throws Exception {
        getFieldDef(obj.getClass(), fieldName).set(obj, val);
    }

    public static Field getFieldDef(Class<?> clazz, String fieldName) throws Exception {
        return getFieldDef(clazz, fieldName, true);
    }

    public static Field getFieldDef(Class<?> clazz, String fieldName, boolean accessible) throws Exception {
        Field field = null;
        while (clazz != null) {
            try {
                field = clazz.getDeclaredField(fieldName);
                clazz = null;
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        if (field == null) {
            throw new NoSuchFieldException(fieldName);
        }
        if (accessible)
            field.setAccessible(true);
        return field;
    }
}

Related

  1. setField(Object obj, Class fieldOwner, String fieldName, Object value)
  2. setField(Object obj, Field field, Object value)
  3. setField(Object obj, Object value, String fieldName)
  4. setField(Object obj, Object value, String fieldName)
  5. setField(Object obj, String fieldName, Object fieldValue)
  6. setField(Object obj, String fieldname, Object value)
  7. setField(Object obj, String fieldName, Object value)
  8. setField(Object obj, String fieldName, Object value)
  9. setField(Object obj, String fieldName, Object value, Class valueClass)