Java Reflection Field Value Set setFieldValue(Object target, String fname, Class ftype, Object fvalue)

Here you can find the source of setFieldValue(Object target, String fname, Class ftype, Object fvalue)

Description

set Field Value

License

Open Source License

Declaration

public static void setFieldValue(Object target, String fname, Class ftype, Object fvalue) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    public static void setFieldValue(Object target, String fname, Class ftype, Object fvalue) {
        if ((target == null) || (fname == null) || ("".equals(fname))
                || ((fvalue != null) && (!ftype.isAssignableFrom(fvalue.getClass())))) {
            return;
        }//w w w .j  a v a 2s .c  o  m
        Class clazz = target.getClass();
        try {
            Method method = clazz.getDeclaredMethod(
                    "set" + Character.toUpperCase(fname.charAt(0)) + fname.substring(1), new Class[] { ftype });
            if (!Modifier.isPublic(method.getModifiers())) {
                method.setAccessible(true);
            }
            method.invoke(target, new Object[] { fvalue });
        } catch (Exception me) {
            try {
                Field field = clazz.getDeclaredField(fname);
                if (!Modifier.isPublic(field.getModifiers())) {
                    field.setAccessible(true);
                }
                field.set(target, fvalue);
            } catch (Exception fe) {
                fe.printStackTrace();
            }
        }
    }
}

Related

  1. setFieldValue(Object target, String field, Object value)
  2. setFieldValue(Object target, String fieldName, Object fieldValue)
  3. setFieldValue(Object target, String fieldName, Object value)
  4. setFieldValue(Object target, String fieldName, Object value)
  5. setFieldValue(Object target, String fieldName, String fieldValue)
  6. setFieldValue(String fieldName, int fieldValue, Object board)
  7. setFieldValue(String inField, Object inObject, Object inValue)
  8. setFieldValue(String name, Object instance, int value, Class cl)
  9. setFieldValue(String name, String obfuscatedName, Class clazz, Object object, Object value)