public static void setFieldValue ( Object instanceContainingField , String fieldName , Object fieldValue ) { // Find the class containing the field to set Class < ? > targetClass = instanceContainingField . getClass ( ) ; while ( targetClass != null ) { for ( Field field : targetClass . getDeclaredFields ( ) ) { if ( field . getName ( ) . equalsIgnoreCase ( fieldName ) ) { try { boolean isAccessible = field . isAccessible ( ) ; try { field . setAccessible ( true ) ; field . set ( instanceContainingField , fieldValue ) ; } finally { field . setAccessible ( isAccessible ) ; } } catch ( Exception e ) { // This shouldn't happen but if it does then the Component manager will not function properly // and we need to abort. It probably means the Java security manager has been configured to // prevent accessing private fields. throw new RuntimeException ( "Failed to set field [" + fieldName + "] in instance of [" + instanceContainingField . getClass ( ) . getName ( ) + "]. The Java Security Manager has " + "probably been configured to prevent settting private field values. XWiki requires " + "this ability to work." , e ) ; } return ; } } targetClass = targetClass . getSuperclass ( ) ; } }
Sets a value to a field using reflection even if the field is private .