Example usage for java.lang.reflect Array set

List of usage examples for java.lang.reflect Array set

Introduction

In this page you can find the example usage for java.lang.reflect Array set.

Prototype

public static native void set(Object array, int index, Object value)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

Source Link

Document

Sets the value of the indexed component of the specified array object to the specified new value.

Usage

From source file:org.apache.axis2.databinding.utils.ConverterUtil.java

/**
 * @param returnArray/*w w  w  .  j  av a2s. c  o  m*/
 * @param baseArrayClass
 * @param objectList
 */
private static void ConvertToArbitraryObjectArray(Object returnArray, Class baseArrayClass, List objectList) {
    if (!(ADBBean.class.isAssignableFrom(baseArrayClass))) {
        try {
            for (int i = 0; i < objectList.size(); i++) {
                Object o = objectList.get(i);
                if (o == null) {
                    // if the string is null the object value must be null
                    Array.set(returnArray, i, null);
                } else {
                    Array.set(returnArray, i, getObjectForClass(baseArrayClass, o.toString()));
                }

            }
            return;
        } catch (Exception e) {
            //oops! - this cannot be converted fall through and
            //try the other alternative
        }
    }

    try {
        objectList.toArray((Object[]) returnArray);
    } catch (Exception e) {
        //we are over with alternatives - throw the
        //converison exception
        throw new ObjectConversionException(e);
    }
}

From source file:org.apache.ojb.otm.core.ConcreteEditingContext.java

private void setCollectionField(Object obj, PersistentField f, List newCol) {
    Class type = f.getType();//  w ww.  j  a v  a  2  s . c  o m

    if (Collection.class.isAssignableFrom(type)) {
        Collection col = (Collection) f.get(obj);

        if (col == null) {
            if (type == List.class || type == Collection.class) {
                col = new ArrayList();
            } else if (type == Set.class) {
                col = new HashSet();
            } else {
                try {
                    col = (Collection) type.newInstance();
                } catch (Throwable ex) {
                    System.err.println("Cannot instantiate collection field: " + f);
                    ex.printStackTrace();
                    return;
                }
            }
        } else {
            if (col instanceof CollectionProxyDefaultImpl) {
                CollectionProxyDefaultImpl cp = (CollectionProxyDefaultImpl) col;
                if (col instanceof List) {
                    col = new ListProxyDefaultImpl(_pb.getPBKey(), cp.getData().getClass(), null);
                } else if (col instanceof Set) {
                    col = new SetProxyDefaultImpl(_pb.getPBKey(), cp.getData().getClass(), null);
                } else {
                    col = new CollectionProxyDefaultImpl(_pb.getPBKey(), cp.getData().getClass(), null);
                }
                col.clear();
            } else {
                try {
                    col = (Collection) col.getClass().newInstance();
                } catch (Exception ex) {
                    System.err.println("Cannot instantiate collection field: " + f);
                    ex.printStackTrace();
                    return;
                }
            }
        }
        col.addAll(newCol);
        f.set(obj, col);
    } else if (type.isArray()) {
        int length = newCol.size();
        Object array = Array.newInstance(type.getComponentType(), length);

        for (int i = 0; i < length; i++) {
            Array.set(array, i, newCol.get(i));
        }
        f.set(obj, array);
    }
}

From source file:com.github.dozermapper.core.MappingProcessor.java

private Object addToPrimitiveArray(Object srcObj, FieldMap fieldMap, int size, Object srcCollectionValue,
        Object destObj, Class<?> destEntryType) {

    Object result;/* w  w w  . jav a2 s .co  m*/
    Object field = fieldMap.getDestValue(destObj);
    int arraySize = 0;
    if (field == null) {
        result = Array.newInstance(destEntryType, size);
    } else {
        result = Array.newInstance(destEntryType, size + Array.getLength(field));
        arraySize = Array.getLength(field);
        System.arraycopy(field, 0, result, 0, arraySize);
    }
    // primitive arrays are ALWAYS cumulative
    for (int i = 0; i < size; i++) {
        CopyByReferenceContainer copyByReferences = globalConfiguration.getCopyByReferences();
        Object toValue;
        if (srcCollectionValue != null && copyByReferences.contains(srcCollectionValue.getClass())) {
            toValue = srcCollectionValue;
        } else {
            toValue = mapOrRecurseObject(srcObj, Array.get(srcCollectionValue, i), destEntryType, fieldMap,
                    destObj);
        }
        Array.set(result, arraySize, toValue);
        arraySize++;
    }
    return result;
}

From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java

@Override
@SuppressWarnings("unchecked")
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type fulltype,
        ArgumentMatches matches) {// w w  w  . j  av a 2 s .c  o  m
    Class type = makeRawTypeIfNecessary(fulltype);
    Type componentType;
    Object result;

    if (Collection.class.isAssignableFrom(type)) {

        // If this is a generic interface, pick a concrete implementation to create and pass back.
        // Because of type erasure, don't worry about creating one of exactly the correct type.
        if (Modifier.isInterface(type.getModifiers()) || Modifier.isAbstract(type.getModifiers())) {
            if (java.util.List.class.isAssignableFrom(type))
                type = ArrayList.class;
            else if (java.util.Queue.class.isAssignableFrom(type))
                type = java.util.ArrayDeque.class;
            else if (java.util.Set.class.isAssignableFrom(type))
                type = java.util.TreeSet.class;
        }

        componentType = getCollectionComponentType(source.field);
        ArgumentTypeDescriptor componentArgumentParser = parsingEngine
                .selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType));

        Collection collection;
        try {
            collection = (Collection) type.newInstance();
        } catch (InstantiationException e) {
            logger.fatal(
                    "ArgumentParser: InstantiationException: cannot convert field " + source.field.getName());
            throw new ReviewedStingException(
                    "constructFromString:InstantiationException: Failed conversion " + e.getMessage());
        } catch (IllegalAccessException e) {
            logger.fatal(
                    "ArgumentParser: IllegalAccessException: cannot convert field " + source.field.getName());
            throw new ReviewedStingException(
                    "constructFromString:IllegalAccessException: Failed conversion " + e.getMessage());
        }

        for (ArgumentMatch match : matches) {
            for (ArgumentMatch value : match) {
                Object object = componentArgumentParser.parse(parsingEngine, source, componentType,
                        new ArgumentMatches(value));
                collection.add(object);
                // WARNING: Side effect!
                parsingEngine.addTags(object, value.tags);
            }
        }

        result = collection;

    } else if (type.isArray()) {
        componentType = type.getComponentType();
        ArgumentTypeDescriptor componentArgumentParser = parsingEngine
                .selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType));

        // Assemble a collection of individual values used in this computation.
        Collection<ArgumentMatch> values = new ArrayList<ArgumentMatch>();
        for (ArgumentMatch match : matches)
            for (ArgumentMatch value : match)
                values.add(value);

        result = Array.newInstance(makeRawTypeIfNecessary(componentType), values.size());

        int i = 0;
        for (ArgumentMatch value : values) {
            Object object = componentArgumentParser.parse(parsingEngine, source, componentType,
                    new ArgumentMatches(value));
            Array.set(result, i++, object);
            // WARNING: Side effect!
            parsingEngine.addTags(object, value.tags);
        }
    } else
        throw new ReviewedStingException("Unsupported compound argument type: " + type);

    return result;
}

From source file:org.soybeanMilk.core.bean.DefaultGenericConverter.java

/**
 * ???/*w  w w.  j a  v a  2 s .c  o  m*/
 * @param list 
 * @param elementType 
 * @return
 * @date 2012-2-19
 */
protected Object listToArray(List<?> list, Type elementType) {
    Object result = null;

    if (list != null) {
        int size = list.size();

        result = instance(elementType, size);

        for (int i = 0; i < size; i++)
            Array.set(result, i, list.get(i));
    }

    return result;
}

From source file:com.betfair.cougar.netutil.nio.marshalling.SocketRMIMarshallerTest.java

/**
 * Equals methods in generated idd classes don't handle delegates
 * @param result/*from www .  j a va2s. c om*/
 * @return
 * @throws Exception
 */
private Object removeDelegates(Object result) throws Exception {
    if (!(result instanceof Transcribable)) {
        return result;
    }
    Transcribable transcribable = (Transcribable) result;
    final Object[] objects = new Object[transcribable.getParameters().length];
    final int[] index = new int[1];
    transcribable.transcribe(new TranscriptionOutput() {

        @Override
        public void writeObject(Object obj, Parameter param, boolean client) throws Exception {
            if (obj == null) {
                objects[index[0]++] = null;
            } else if (param.getParameterType().getType() == Type.OBJECT) {
                objects[index[0]++] = removeDelegates(obj);
            } else if (param.getParameterType().getType() == Type.LIST) {
                if (obj.getClass().isArray()) {
                    objects[index[0]] = Array.newInstance(
                            param.getParameterType().getComponentTypes()[0].getImplementationClass(),
                            Array.getLength(obj));
                    for (int i = 0, limit = Array.getLength(obj); i < limit; i++) {
                        Array.set(objects[index[0]], i, removeDelegates(Array.get(obj, i)));
                    }
                    index[0]++;
                } else {
                    List list = (List) obj;
                    objects[index[0]] = new ArrayList();
                    for (Object o : list) {
                        ((List) objects[index[0]]).add(removeDelegates(o));
                    }
                    index[0]++;
                }
            } else if (param.getParameterType().getType() == Type.SET) {
                Set set = (Set) obj;
                objects[index[0]] = new HashSet();
                for (Object o : set) {
                    ((Set) objects[index[0]]).add(removeDelegates(o));
                }
                index[0]++;
            } else if (param.getParameterType().getType() == Type.MAP) {
                Map<Object, Object> map = (Map) obj;
                objects[index[0]] = new HashMap();
                for (Entry entry : map.entrySet()) {
                    ((Map) objects[index[0]]).put(removeDelegates(entry.getKey()),
                            removeDelegates(entry.getValue()));
                }
                index[0]++;
            } else {
                objects[index[0]++] = obj;
            }

        }
    }, TranscribableParams.getAll(), false);

    Transcribable newObject = (Transcribable) result.getClass().newInstance();
    index[0] = 0;
    newObject.transcribe(new TranscriptionInput() {

        @Override
        public <T> T readObject(Parameter param, boolean client) throws Exception {
            return (T) objects[index[0]++];

        }
    }, TranscribableParams.getAll(), false);

    return newObject;
}

From source file:com.google.ratel.util.RatelUtils.java

private static Object createDeepInstance(Class type, Set<Class> cyclicDetector) {
    cyclicDetector.add(type);//w w w .j  a v  a2 s .c o  m
    //System.out.println("Depth: " + callingDepth);

    try {
        Object obj = null;

        // Handle primitives
        if (defaultValues.containsKey(type)) {
            Object defaultValue = defaultValues.get(type);
            obj = defaultValue;

            // Handle Arrays
        } else if (type.isArray()) {
            Class arrayType = type.getComponentType();

            // Check cyclic dependency
            if (!cyclicDetector.contains(arrayType)) {

                Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector);
                Object value = createDeepInstance(arrayType, localCyclicDetector);
                obj = Array.newInstance(arrayType, 1);
                Array.set(obj, 0, value);
            }

        } else {
            // Handle pojo
            obj = type.newInstance();

            List<Field> fullFieldList = getAllFields(type);

            for (Field field : fullFieldList) {
                Class fieldType = field.getType();

                // Check for cyclic dependency
                if (!cyclicDetector.contains(fieldType)) {
                    Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector);
                    Object fieldObj = createDeepInstance(fieldType, localCyclicDetector);
                    if (!Modifier.isPublic(field.getModifiers())) {
                        field.setAccessible(true);
                    }

                    field.set(obj, fieldObj);

                    if (!Modifier.isPublic(field.getModifiers())) {
                        field.setAccessible(false);
                    }
                }

            }
        }
        return obj;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.beans.BeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;/*  w  w  w  .  jav  a 2  s .  c o  m*/
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // TODO: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.resolvedDescriptor;
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().resolvedDescriptor = pd;
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())
                                && !readMethod.isAccessible()) {
                            if (System.getSecurityManager() != null) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            } else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceClient.java

/**
 * Invokes a custom API/*from w ww  . j  a va2  s. c  o  m*/
 *
 * @param apiName    The API name
 * @param body       The object to send as the request body
 * @param httpMethod The HTTP Method used to invoke the API
 * @param parameters The query string parameters sent in the request
 * @param clazz      The API result class
 */
public <E> ListenableFuture<E> invokeApi(String apiName, Object body, String httpMethod,
        List<Pair<String, String>> parameters, final Class<E> clazz) {
    if (clazz == null) {
        throw new IllegalArgumentException("clazz cannot be null");
    }

    JsonElement json = null;
    if (body != null) {
        if (body instanceof JsonElement) {
            json = (JsonElement) body;
        } else {
            json = getGsonBuilder().create().toJsonTree(body);
        }
    }

    final SettableFuture<E> future = SettableFuture.create();
    ListenableFuture<JsonElement> internalFuture = this.invokeApiInternal(apiName, json, httpMethod, parameters,
            EnumSet.of(MobileServiceFeatures.TypedApiCall));

    Futures.addCallback(internalFuture, new FutureCallback<JsonElement>() {
        @Override
        public void onFailure(Throwable e) {
            future.setException(e);
        }

        @Override
        @SuppressWarnings("unchecked")
        public void onSuccess(JsonElement jsonElement) {
            Class<?> concreteClass = clazz;
            if (clazz.isArray()) {
                concreteClass = clazz.getComponentType();
            }

            List<?> entities = JsonEntityParser.parseResults(jsonElement, getGsonBuilder().create(),
                    concreteClass);

            if (clazz.isArray()) {
                E array = (E) Array.newInstance(concreteClass, entities.size());
                for (int i = 0; i < entities.size(); i++) {
                    Array.set(array, i, entities.get(i));
                }

                future.set(array);
            } else {
                future.set((E) entities.get(0));
            }
        }
    });

    return future;
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException {
    net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue(
            "", null);
    AfxBeanUtils.copySamePropertyValue(pv2, pv);
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;/*from  w  ww. j  a v  a2  s.  c  o  m*/
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // #TO#DO#: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.getResolvedDescriptor();
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().setResolvedDescriptor(pd);
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.getConversionNecessary())) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())
                                && !readMethod.isAccessible()) {
                            if (System.getSecurityManager() != null) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            } else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}