Here you can find the source of setField(Object obj, Object value, String fieldName)
Parameter | Description |
---|---|
obj | The object to set the field in |
value | The value to set the field to |
fieldName | The field name |
public static void setField(Object obj, Object value, String fieldName)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Field; public class Main { /**//from w w w . j a v a2 s.c o m * Sets the value of a field * @param obj The object to set the field in * @param value The value to set the field to * @param fieldName The field name */ public static void setField(Object obj, Object value, String fieldName) { try { getField(obj.getClass(), fieldName).set(obj, value); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } /** * Gets the value of a field * * @param obj The object to get the field from * @param fieldName The field name to get * @return null if there is no field or an exception was thrown */ public static Object getField(Object obj, String fieldName) { try { return getField(obj.getClass(), fieldName).get(obj); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } /** * Retrieves a field * * @param cl The class to retrieve the field from * @param fieldName The name of the field * @return null if there is no field or an exception was thrown */ public static Field getField(Class<?> cl, String fieldName) { try { Field field = cl.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return null; } public static Class<?> getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } }