Java Reflection Field Set setFieldIfExists(final Object instance, final String fieldName, final Object value)

Here you can find the source of setFieldIfExists(final Object instance, final String fieldName, final Object value)

Description

set Field If Exists

License

Open Source License

Declaration

public static boolean setFieldIfExists(final Object instance, final String fieldName, final Object value) 

Method Source Code

//package com.java2s;

import java.lang.reflect.*;

public class Main {
    public static boolean setFieldIfExists(final Object instance, final String fieldName, final Object value) {
        try {//from   w w  w. j  av  a  2s  .  c o  m
            final Field f = instance.getClass().getField(fieldName);
            if (value instanceof Boolean || f.getType().isInstance(value)) {
                f.set(instance, value);
                return true;
            } else {
                System.out.println(instance.getClass() + " '" + fieldName + "' field not assignable with "
                        + value.getClass() + ", it's a: " + f.getType());
            }
        } catch (final IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (final NoSuchFieldException nsfe) {
            // OK - throw new RuntimeException(instance.getClass()+" has no '"+fieldName+"' field", nsfe);
        }
        return false;
    }
}

Related

  1. setFieldBySomeMethod(List setMethods, Object object, Object value)
  2. setFieldContent(final Object obj, final String name, final Object value)
  3. setFieldEditable(Class clazz, String fieldName)
  4. setFieldForAnnotation(Object target, Class annotation, Object value)
  5. setFieldHelper(Object o, String name, Object v)
  6. setFieldObject(Class clazz, String field, Object object, Object newObj)
  7. setFieldObject(Class target, Object targetObject, String fieldName, Object object)
  8. setFieldObjectValue(Class targetClass, Object target, String fieldName, Object value)
  9. setFieldPrimitive(Object target, Field field, Object value)