Java Reflection Field Set setField(Object object, String fieldName, Object value)

Here you can find the source of setField(Object object, String fieldName, Object value)

Description

set Field

License

Open Source License

Declaration

public static void setField(Object object, String fieldName, Object value) 

Method Source Code


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

import java.lang.reflect.*;

public class Main {
    public static void setField(Object object, String fieldName, Object value) {
        try {/*from   w  w  w. j  a v  a 2s  .  c om*/
            Field field = object.getClass().getField(fieldName);
            field.set(object, value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static Object getField(Object object, String fieldName) {
        try {
            Field field = object.getClass().getField(fieldName);
            return field.get(object);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static Class<?> getClass(String clazz) {
        try {
            return Class.forName(clazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. setField(Object object, String fieldName, Object newValue)
  2. setField(Object object, String fieldName, Object newValue, boolean isFindDeclaredField, boolean isUpwardFind)
  3. setField(Object object, String fieldName, Object value)
  4. setField(Object object, String fieldName, Object value)
  5. setField(Object object, String fieldName, Object value)
  6. setField(Object object, String name, boolean value)
  7. setField(Object object, String name, Object value)
  8. setField(Object object, String name, Object value)
  9. setField(Object owner, String name, Object newValue, Class definedIn)