Here you can find the source of setField(Object owner, String targetClass, String fieldName, Object value)
Parameter | Description |
---|---|
owner | : target object |
classLevel | : 0 means itself, 1 means it's father, and so on... |
fieldName | : name of the target field |
value | : new value of the target field |
Parameter | Description |
---|---|
NoSuchFieldException | an exception |
SecurityException | an exception |
IllegalAccessException | an exception |
IllegalArgumentException | an exception |
public static void setField(Object owner, String targetClass, String fieldName, Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException
//package com.java2s; /*/*from ww w . j a v a 2 s . c om*/ * Copyright (C) 2011 Baidu.com Inc * * 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 { /** * Set object's field with custom value even it's private. * * @param owner * : target object * @param classLevel * : 0 means itself, 1 means it's father, and so on... * @param fieldName * : name of the target field * @param value * : new value of the target field * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException */ public static void setField(Object owner, String targetClass, String fieldName, Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Class<?> ownerclass = getTargetclass(owner, targetClass); Field field = ownerclass.getDeclaredField(fieldName); if (!field.isAccessible()) { field.setAccessible(true); } field.set(owner, value); } private static Class<?> getTargetclass(Object owner, String targetClass) { try { return null == targetClass ? owner.getClass() : Class.forName(targetClass); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } }