Java Reflection Field Value Set setFieldValue(Object bean, Field field, Object value)

Here you can find the source of setFieldValue(Object bean, Field field, Object value)

Description

set Field Value

License

Apache License

Declaration

public static void setFieldValue(Object bean, Field field, Object value)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException 

Method Source Code


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

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void setFieldValue(Object bean, Field field, Object value)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = null;//  w w  w .j  a v a2s .  c  o  m
        method = getSetMethod(bean.getClass(), field);
        if (method == null) {
            throw new NoSuchMethodException("can not find the set method");
        } else {
            method.invoke(bean, new Object[] { value });
        }
    }

    public static Method getSetMethod(Class<?> bean, Field field) {
        String isMethodName = "set" + toUpperCaseFirstChar(field.getName());

        try {
            return bean.getMethod(isMethodName, new Class[] { field.getType() });
        } catch (NoSuchMethodException var4) {
            System.out.println(isMethodName + " not found");
            return null;
        }
    }

    public static String toUpperCaseFirstChar(String string) {
        return string == null ? null : string.toUpperCase().charAt(0) + string.substring(1);
    }
}

Related

  1. setFieldValue(final Object object, final String fieldName, final Object value)
  2. setFieldValue(final Object object, final String fieldName, final Object value)
  3. setFieldValue(final Object object, final String fieldName, final Object value)
  4. setFieldValue(Map map, Class cls)
  5. setFieldValue(Object bean, Field field, Object value)
  6. setFieldValue(Object bean, String field, Object value)
  7. setFieldValue(Object host, Field f, Object value)
  8. setFieldValue(Object input, Object value, String fieldName)
  9. setFieldValue(Object instance, Field field, Object value)