Java Reflection Field Set setFieldVal(Object object, String name, Object val)

Here you can find the source of setFieldVal(Object object, String name, Object val)

Description

set Field Val

License

Apache License

Declaration

public static void setFieldVal(Object object, String name, Object val) 

Method Source Code


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

import java.lang.reflect.Field;

public class Main {
    public static void setFieldVal(Object object, String name, Object val) {
        Field field = getFieldByName(object.getClass(), name);
        field.setAccessible(true);//from  w  w  w .j a  v a  2s  . c o m
        try {
            field.set(object, val);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static Field getFieldByName(Class<?> modelClass, String name) {
        Class<?> clazz = cloneClass(modelClass);
        Field field = null;
        for (int i = 0; i < 100; i++) {
            try {
                field = clazz.getDeclaredField(name);
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
            if (field != null)
                break;
        }
        return field;
    }

    public static Class<?> cloneClass(Class<?> clazz) {
        Class<?> newClazz = null;
        try {
            newClazz = Class.forName(clazz.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return newClazz;
    }
}

Related

  1. setFieldObjectValue(Class targetClass, Object target, String fieldName, Object value)
  2. setFieldPrimitive(Object target, Field field, Object value)
  3. setFields(Field field, Object value, Object config)
  4. setFields(final Map fields, final Object target)
  5. setFieldStatic(final Object pBean, final String fieldname, final Object pInject)
  6. setFieldValeByType(Field field, Object obj, String value)
  7. setFieldViaReflection(String fieldName, V value, T classInstance)
  8. setFieldVisible( Class classToModify, String fieldName)
  9. setFieldWithReflection(Object object, String fieldName, Object fieldValue)