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.kordamp.ezmorph.bean.MorphDynaBean.java

public void set(String name, int index, Object value) {
    DynaProperty dynaProperty = getDynaProperty(name);

    Class type = dynaProperty.getType();
    if (!type.isArray() && !List.class.isAssignableFrom(type)) {
        throw new MorphException("Non-Indexed property name: " + name + " index: " + index);
    }/*from   w  w w  .ja v  a 2s  .  c  om*/

    Object prop = dynaValues.get(name);
    if (prop == null) {
        if (List.class.isAssignableFrom(type)) {
            prop = new ArrayList();
        } else {
            prop = Array.newInstance(type.getComponentType(), index + 1);
        }
        dynaValues.put(name, prop);
    }

    if (prop.getClass().isArray()) {
        if (index >= Array.getLength(prop)) {
            Object tmp = Array.newInstance(type.getComponentType(), index + 1);
            System.arraycopy(prop, 0, tmp, 0, Array.getLength(prop));
            prop = tmp;
            dynaValues.put(name, tmp);
        }
        Array.set(prop, index, value);
    } else if (prop instanceof List) {
        List l = (List) prop;
        if (index >= l.size()) {
            for (int i = l.size(); i <= index + 1; i++) {
                l.add(null);
            }
        }
        ((List) prop).set(index, value);
    }
}

From source file:org.openmobster.core.mobileObject.TestBeanSyntax.java

private Object initializeIndexedProperty(Object parentObject, String property,
        PropertyDescriptor propertyMetaData) throws Exception {
    Object element = null;/*from w ww  .j  a  va  2 s . c  o  m*/

    //Find the Class of the elementType
    Class elementType = null;

    if (!propertyMetaData.getPropertyType().isArray()) {
        ParameterizedType returnType = (ParameterizedType) propertyMetaData.getReadMethod()
                .getGenericReturnType();
        Type[] actualTypes = returnType.getActualTypeArguments();
        for (Type actualType : actualTypes) {
            elementType = (Class) actualType;
        }
    } else {
        elementType = propertyMetaData.getPropertyType().getComponentType();
    }

    //An IndexedProperty
    Object indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());

    //Initialize the IndexedProperty (An Array or Collection)
    if (indexedProperty == null) {
        if (propertyMetaData.getPropertyType().isArray()) {
            //TODO: Remove hardcoded array size                     
            PropertyUtils.setProperty(parentObject, propertyMetaData.getName(),
                    Array.newInstance(elementType, 1));
        } else {
            //Handle Collection Construction
            PropertyUtils.setProperty(parentObject, propertyMetaData.getName(), new ArrayList());
        }
        indexedProperty = PropertyUtils.getProperty(parentObject, propertyMetaData.getName());
    }

    //Check to see if the index specified by the field requires creation of new
    //element
    try {
        element = PropertyUtils.getIndexedProperty(parentObject, property);
    } catch (IndexOutOfBoundsException iae) {
        Object newlyInitialized = elementType.newInstance();

        if (!propertyMetaData.getPropertyType().isArray()) {
            ((Collection) indexedProperty).add(newlyInitialized);
        } else {
            //TODO: Remove hardcoded array index
            Array.set(indexedProperty, 0, newlyInitialized);
        }

        element = newlyInitialized;
    }

    return element;
}

From source file:com.comcast.cereal.engines.AbstractCerealEngine.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> T deCerealize(Object cereal, Class<T> clazz) throws CerealException {
    ObjectCache objectCache = new ObjectCache(settings);
    try {/*w  ww.  java  2 s .c o  m*/
        if (cereal instanceof List && clazz.isArray()) {
            List<Object> cerealList = (List) cereal;
            Class arrayType = clazz.getComponentType();
            Cerealizer cerealizer = cerealFactory.getCerealizer(arrayType);

            T array = (T) Array.newInstance(arrayType, cerealList.size());
            for (int i = 0; i < cerealList.size(); i++) {
                Array.set(array, i, cerealizer.deCerealize(cerealList.get(i), objectCache));
            }

            return array;
        } else {
            Class<?> runtimeClass = cerealFactory.getRuntimeClass(cereal);
            Cerealizer cerealizer = cerealFactory.getCerealizer(clazz);

            if ((runtimeClass != null) && clazz.isAssignableFrom(runtimeClass)) {
                /** need to check if the runtime class is a subclass of the given class
                 *  or we will get a class cast exception when we return it */
                cerealizer = cerealFactory.getRuntimeCerealizer(cereal, cerealizer);
            }
            return (T) cerealizer.deCerealize(cereal, objectCache);
        }
    } finally {
        objectCache.resetCache();
    }
}

From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java

/**
 * recursively populate array out of hierarchy of JSON Objects
 *
 * @param arrayClass original array class
 * @param json      json object in question
 * @return/* w ww .  j av  a2 s  . c o m*/
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object populateRecursive(Class arrayClass, Object json) throws JSONException,
        InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
    if (arrayClass.isArray() && json instanceof JSONArray) {
        final int length = ((JSONArray) json).length();
        final Class componentType = arrayClass.getComponentType();
        Object retval = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(retval, i, populateRecursive(componentType, ((JSONArray) json).get(i)));
        }
        return retval;
    } else {
        // this is leaf object, JSON needs to be unmarshalled,
        if (json instanceof JSONObject) {
            return unmarshall((JSONObject) json, arrayClass);
        } else {
            // while all others can be returned verbatim
            return json;
        }
    }
}

From source file:org.apache.sling.models.impl.injectors.OSGiServiceInjector.java

private Object getValue(Object adaptable, Type type, String filterString,
        DisposalCallbackRegistry callbackRegistry) {
    if (type instanceof Class) {
        Class<?> injectedClass = (Class<?>) type;
        if (injectedClass.isArray()) {
            Object[] services = getServices(adaptable, injectedClass.getComponentType(), filterString,
                    callbackRegistry);/*w ww.j  ava2s . c  o m*/
            if (services == null) {
                return null;
            }
            Object arr = Array.newInstance(injectedClass.getComponentType(), services.length);
            for (int i = 0; i < services.length; i++) {
                Array.set(arr, i, services[i]);
            }
            return arr;
        } else {
            return getService(adaptable, injectedClass, filterString, callbackRegistry);
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType ptype = (ParameterizedType) type;
        if (ptype.getActualTypeArguments().length != 1) {
            return null;
        }
        Class<?> collectionType = (Class<?>) ptype.getRawType();
        if (!(collectionType.equals(Collection.class) || collectionType.equals(List.class))) {
            return null;
        }

        Class<?> serviceType = (Class<?>) ptype.getActualTypeArguments()[0];
        Object[] services = getServices(adaptable, serviceType, filterString, callbackRegistry);
        if (services == null) {
            return null;
        }
        return Arrays.asList(services);
    } else {
        log.warn("Cannot handle type {}", type);
        return null;
    }
}

From source file:es.caib.zkib.jxpath.util.BasicTypeConverter.java

/**
 * Converts the supplied object to the specified
 * type. Throws a runtime exception if the conversion is
 * not possible.//from w ww .  j a v a2 s.co  m
 * @param object to convert
 * @param toType destination class
 * @return converted object
 */
public Object convert(Object object, final Class toType) {
    if (object == null) {
        return toType.isPrimitive() ? convertNullToPrimitive(toType) : null;
    }

    if (toType == Object.class) {
        if (object instanceof NodeSet) {
            return convert(((NodeSet) object).getValues(), toType);
        }
        if (object instanceof Pointer) {
            return convert(((Pointer) object).getValue(), toType);
        }
        return object;
    }
    final Class useType = TypeUtils.wrapPrimitive(toType);
    Class fromType = object.getClass();

    if (useType.isAssignableFrom(fromType)) {
        return object;
    }

    if (fromType.isArray()) {
        int length = Array.getLength(object);
        if (useType.isArray()) {
            Class cType = useType.getComponentType();

            Object array = Array.newInstance(cType, length);
            for (int i = 0; i < length; i++) {
                Object value = Array.get(object, i);
                Array.set(array, i, convert(value, cType));
            }
            return array;
        }
        if (Collection.class.isAssignableFrom(useType)) {
            Collection collection = allocateCollection(useType);
            for (int i = 0; i < length; i++) {
                collection.add(Array.get(object, i));
            }
            return unmodifiableCollection(collection);
        }
        if (length > 0) {
            Object value = Array.get(object, 0);
            return convert(value, useType);
        }
        return convert("", useType);
    }
    if (object instanceof Collection) {
        int length = ((Collection) object).size();
        if (useType.isArray()) {
            Class cType = useType.getComponentType();
            Object array = Array.newInstance(cType, length);
            Iterator it = ((Collection) object).iterator();
            for (int i = 0; i < length; i++) {
                Object value = it.next();
                Array.set(array, i, convert(value, cType));
            }
            return array;
        }
        if (Collection.class.isAssignableFrom(useType)) {
            Collection collection = allocateCollection(useType);
            collection.addAll((Collection) object);
            return unmodifiableCollection(collection);
        }
        if (length > 0) {
            Object value;
            if (object instanceof List) {
                value = ((List) object).get(0);
            } else {
                Iterator it = ((Collection) object).iterator();
                value = it.next();
            }
            return convert(value, useType);
        }
        return convert("", useType);
    }
    if (object instanceof NodeSet) {
        return convert(((NodeSet) object).getValues(), useType);
    }
    if (object instanceof Pointer) {
        return convert(((Pointer) object).getValue(), useType);
    }
    if (useType == String.class) {
        return object.toString();
    }
    if (object instanceof Boolean) {
        if (Number.class.isAssignableFrom(useType)) {
            return allocateNumber(useType, ((Boolean) object).booleanValue() ? 1 : 0);
        }
        if ("java.util.concurrent.atomic.AtomicBoolean".equals(useType.getName())) {
            try {
                return useType.getConstructor(new Class[] { boolean.class })
                        .newInstance(new Object[] { object });
            } catch (Exception e) {
                throw new JXPathTypeConversionException(useType.getName(), e);
            }
        }
    }
    if (object instanceof Number) {
        double value = ((Number) object).doubleValue();
        if (useType == Boolean.class) {
            return value == 0.0 ? Boolean.FALSE : Boolean.TRUE;
        }
        if (Number.class.isAssignableFrom(useType)) {
            return allocateNumber(useType, value);
        }
    }
    if (object instanceof String) {
        Object value = convertStringToPrimitive(object, useType);
        if (value != null || "".equals(object)) {
            return value;
        }
    }

    Converter converter = ConvertUtils.lookup(useType);
    if (converter != null) {
        return converter.convert(useType, object);
    }

    throw new JXPathTypeConversionException("Cannot convert " + object.getClass() + " to " + useType);
}

From source file:ArrayUtils.java

/**
 * Moves an element in a primitive array from one index to another
 * //from  ww w.  j  a v a 2  s.co  m
 * @param anArray
 *            The array to move an element within
 * @param from
 *            The index of the element to move
 * @param to
 *            The index to move the element to
 * @return The original array
 */
public static Object moveP(Object anArray, int from, int to) {
    if (anArray instanceof Object[])
        return move((Object[]) anArray, from, to);
    final Object element = Array.get(anArray, from);
    for (; from < to; from++)
        Array.set(anArray, from, Array.get(anArray, from + 1));
    for (; from > to; from--)
        Array.set(anArray, from, Array.get(anArray, from - 1));
    Array.set(anArray, to, element);
    return anArray;
}

From source file:sf.net.experimaestro.server.JsonRPCMethods.java

private int convert(Object p, Arguments description, int score, List args, int index) {
    Object o;/*from   w ww .j  a v  a 2s  . c  o  m*/
    if (p instanceof JSONObject)
        // If p is a map, then use the json name of the argument
        o = ((JSONObject) p).get(description.getArgument(index).name());
    else if (p instanceof JSONArray)
        // if it is an array, then map it
        o = ((JSONArray) p).get(index);
    else {
        // otherwise, suppose it is a one value array
        if (index > 0)
            return Integer.MIN_VALUE;
        o = p;
    }

    final Class aType = description.getType(index);

    if (o == null) {
        if (description.getArgument(index).required())
            return Integer.MIN_VALUE;

        return score - 10;
    }

    if (aType.isArray()) {
        if (o instanceof JSONArray) {
            final JSONArray array = (JSONArray) o;

            final ArrayList arrayObjects;
            if (args != null) {
                arrayObjects = new ArrayList(array.size());
                for (int i = 0; i < array.size(); i++) {
                    arrayObjects.add(null);
                }
            } else {
                arrayObjects = null;
            }

            Arguments arguments = new Arguments() {
                @Override
                public RPCArgument getArgument(int i) {
                    return new RPCArrayArgument();
                }

                @Override
                public Class<?> getType(int i) {
                    return aType.getComponentType();
                }

                @Override
                public int size() {
                    return array.size();
                }
            };

            for (int i = 0; i < array.size() && score > Integer.MIN_VALUE; i++) {
                score = convert(array.get(i), arguments, score, arrayObjects, i);
            }

            if (args != null && score > Integer.MIN_VALUE) {
                final Object a1 = Array.newInstance(aType.getComponentType(), array.size());
                for (int i = 0; i < array.size(); i++) {
                    Array.set(a1, i, arrayObjects.get(i));
                }
                args.set(index, a1);
            }
            return score;
        }
        return Integer.MIN_VALUE;
    }

    if (aType.isAssignableFrom(o.getClass())) {
        if (args != null)
            args.set(index, o);
        return score;
    }

    if (o.getClass() == Long.class && aType == Integer.class) {
        if (args != null)
            args.set(index, ((Long) o).intValue());
        return score - 1;
    }

    return Integer.MIN_VALUE;
}

From source file:com.evolveum.midpoint.prism.PrismProperty.java

/**
  * Type override, also for compatibility.
  *///from   w  w  w  .ja  v a2 s  . c om
public <X> X[] getRealValuesArray(Class<X> type) {
    X[] valuesArrary = (X[]) Array.newInstance(type, getValues().size());
    for (int j = 0; j < getValues().size(); ++j) {
        Object avalue = getValues().get(j).getValue();
        Array.set(valuesArrary, j, avalue);
    }
    return valuesArrary;
}

From source file:ArrayUtils.java

/**
 * <p>Inserts the specified element at the specified position in the array. 
 * Shifts the element currently at that position (if any) and any subsequent
 * elements to the right (adds one to their indices).</p>
 *
 * <p>This method returns a new array with the same elements of the input
 * array plus the given element on the specified position. The component 
 * type of the returned array is always the same as that of the input 
 * array.</p>// w w w . j  a  va2s  . c o m
 *
 * <p>If the input array is <code>null</code>, a new one element array is returned
 *  whose component type is the same as the element.</p>
 * 
 * <pre>
 * ArrayUtils.insert(null, 0, null)      = [null]
 * ArrayUtils.insert(null, 0, "a")       = ["a"]
 * ArrayUtils.insert(["a"], 1, null)     = ["a", null]
 * ArrayUtils.insert(["a"], 1, "b")      = ["a", "b"]
 * ArrayUtils.insert(["a", "b"], 3, "c") = ["a", "b", "c"]
 * </pre>
 * 
 * @param array  the array to add the element to, may be <code>null</code>
 * @param index  the position of the new object
 * @param element  the object to add
 * @return A new array containing the existing elements and the new element
 * @throws IndexOutOfBoundsException if the index is out of range 
 * (index < 0 || index > array.length).
 */
@SuppressWarnings("unchecked")
public static <T> T[] insert(final Object array, final int index, final Object element) {
    if (array == null) {
        if (index != 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
        }
        Object joinedArray = Array.newInstance(element != null ? element.getClass() : Object.class, 1);
        Array.set(joinedArray, 0, element);
        return (T[]) joinedArray;
    }
    int length = getLength(array);
    if (index > length || index < 0) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
    }
    Object result = Array.newInstance(array.getClass().getComponentType(), length + 1);
    System.arraycopy(array, 0, result, 0, index);
    Array.set(result, index, element);
    if (index < length) {
        System.arraycopy(array, index, result, index + 1, length - index);
    }
    return (T[]) result;
}