Here you can find the source of setField(Object obj, String fieldName, Object fieldValue)
Parameter | Description |
---|---|
obj | Object to be modified |
fieldName | name of object's field |
fieldValue | value to be set for field |
Parameter | Description |
---|---|
SecurityException | an exception |
NoSuchFieldException | an exception |
IllegalArgumentException | an exception |
IllegalAccessException | an exception |
public static void setField(Object obj, String fieldName, Object fieldValue) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException
//package com.java2s; /*/*from w ww. j a va2 s . c o m*/ * Copyright 2000-2013 JetBrains s.r.o. * * 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 { /** * Utility to set field in object if there is no public setter for it. * It's not recommended to use this method. * FIXME: remove this workaround after gradle API changed * * @param obj Object to be modified * @param fieldName name of object's field * @param fieldValue value to be set for field * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void setField(Object obj, String fieldName, Object fieldValue) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { final Field field = obj.getClass().getDeclaredField(fieldName); final boolean isAccessible = field.isAccessible(); field.setAccessible(true); field.set(obj, fieldValue); field.setAccessible(isAccessible); } }