Java Reflection Field Set setField(Object target, String fieldName, Class fieldType, T value)

Here you can find the source of setField(Object target, String fieldName, Class fieldType, T value)

Description

set Field

License

Apache License

Declaration

public static <T> void setField(Object target, String fieldName, Class<T> fieldType, T value) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Field;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main {
    public static <T> void setField(Object target, String fieldName, Class<T> fieldType, T value) {
        Field field = findField(target.getClass(), fieldName, fieldType);
        if (field == null) {
            throw new RuntimeException("unknown given field '" + fieldName + "'");
        }/*  w  w w .j  av a  2  s .c o  m*/

        makeAccessible(field);
        try {
            field.set(target, value);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static Field findField(Class<?> clazz, String name, Class<?> type) {
        Class<?> searchType = clazz;
        while (!Object.class.equals(searchType) && searchType != null) {
            Field[] fields = searchType.getDeclaredFields();
            for (Field field : fields) {
                if ((name == null || name.equals(field.getName()))
                        && (type == null || type.equals(field.getType()))) {
                    return field;
                }
            }
            searchType = searchType.getSuperclass();
        }
        return null;
    }

    private static void makeAccessible(Field field) {
        if ((!Modifier.isPublic(field.getModifiers())
                || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
                || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
            field.setAccessible(true);
        }
    }

    private static void makeAccessible(Method method) {
        if ((!Modifier.isPublic(method.getModifiers())
                || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
            method.setAccessible(true);
        }
    }
}

Related

  1. setField(Object service, String name, Object obj)
  2. setField(Object source, String fieldName, Object value)
  3. setField(Object sourceObj, Object targetObj, Field valueField, List targetFields)
  4. setField(Object target, Field field, Object value)
  5. setField(Object target, Field field, Object value)
  6. setField(Object target, String fieldname, Object value)
  7. setField(Object target, String name, Object value)
  8. setField(Object target, String name, Object value)
  9. setField(Object target, String name, Object value)