Java Reflection Field Set setField(String fieldName, Object instance, Class instanceClass, Object value)

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

Description

set Field

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
    public static void setField(String fieldName, Object instance, Class instanceClass, Object value) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2005-2012 eBay Inc.//from  w w w  . j  ava 2s  .co m
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 *******************************************************************************/

import java.lang.reflect.Field;

public class Main {
    @SuppressWarnings("unchecked")
    public static void setField(String fieldName, Object instance, Class instanceClass, Object value) {
        if (instanceClass == null) {
            throw new RuntimeException("NoSuchField: " + fieldName);
        }
        try {
            Field field = instanceClass.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(instance, value);
        } catch (NoSuchFieldException e) {
            setField(fieldName, instance, instanceClass.getSuperclass(), value);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static void setField(String fieldName, Object instance, Object value) {
        setField(fieldName, instance, instance.getClass(), value);
    }
}

Related

  1. setField(Object target, String name, Object value)
  2. setField(Object target, String name, Object value)
  3. setField(Object targetObject, String fieldName, Object value, boolean failIfError)
  4. setField(String field, Object object, Object value)
  5. setField(String field, Object value)
  6. setField(String fieldName, Object instance, Object value)
  7. setField(String name, Object target, Object value)
  8. setField(String name, Object target, Object value)
  9. setField(T object, Field field, ResourceBundle bundle)