Here you can find the source of setField(Object o, String fieldName, Object value)
Parameter | Description |
---|---|
o | The object that contains the field |
fieldName | The name of the field |
value | The new value |
public static Object setField(Object o, String fieldName, Object value)
//package com.java2s; /*//from w w w. j av a2 s . c om * * Copyright 2016,2017 DTCC, Fujitsu Australia Software Technology, IBM - All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import java.lang.reflect.Field; public class Main { /** * Sets the value of a field on an object * * @param o The object that contains the field * @param fieldName The name of the field * @param value The new value * @return The previous value of the field */ public static Object setField(Object o, String fieldName, Object value) { Object oldVal = null; try { final Field field = getFieldInt(o.getClass(), fieldName); field.setAccessible(true); oldVal = field.get(o); field.set(o, value); } catch (Exception e) { throw new RuntimeException("Cannot get value of field " + fieldName, e); } return oldVal; } private static Field getFieldInt(Class o, String name) throws NoSuchFieldException { Field ret; try { ret = o.getDeclaredField(name); } catch (NoSuchFieldException e) { Class superclass = o.getSuperclass(); if (null != superclass) { ret = getFieldInt(superclass, name); } else { throw e; } } ret.setAccessible(true); return ret; } }