Here you can find the source of setField(Object obj, String name, Object value)
Parameter | Description |
---|---|
obj | Object whose attribute value to set. |
name | Name of the attribute to retrieve. |
value | Value to set the attribute to; can bei either an object, a wrapper for simple data types, or the stringified value of a simple data type. |
public static boolean setField(Object obj, String name, Object value)
//package com.java2s; /*/*from www . ja v a 2 s. com*/ * ClassHelper.java * * Copyright (C) August Mayer, 2001-2004. All rights reserved. * Please consult the Boone LICENSE file for additional rights granted to you. * * Created on 16. Juni 2004, 22:57 */ import java.lang.reflect.Method; public class Main { /** * Set the value of this parameter. * The value can either be a suitable Java wrapper object, * or a String containing the stringified value of a simple data type. * * @param obj Object whose attribute value to set. * @param name Name of the attribute to retrieve. * @param value Value to set the attribute to; can bei either an object, a wrapper * for simple data types, or the stringified value of a simple data type. * * @return True if it worked, false else. */ public static boolean setField(Object obj, String name, Object value) { // first, find a setter method // note: if we find a method with the setter name, but with incompatible // parameter signature, we just try to call it anyway, which fails, then continue; // the right setter should come along eventually. String setterName = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1); Method[] methods = obj.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getName().equals(setterName)) { try { methods[i].invoke(obj, new Object[] { value }); return true; // it worked?! YAY! } catch (Exception e) { } // just forget this and try again } } try { // then try to set the thing directly obj.getClass().getDeclaredField(name).set(obj, value); return true; } catch (Exception e) { return false; } } }