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.code_house.service.jolokia.Jolokia.java

private Object map(Class<?> type, Object value) {
    if (type.isArray()) {
        JSONArray array = (JSONArray) value;
        Object[] javaArray = (Object[]) Array.newInstance(type.getComponentType(), array.size());
        int index = 0;
        for (Object o : array) {
            Array.set(javaArray, index++, map(type.getComponentType(), o));
        }//from  w  w w .  j  a  va2 s.c  o m
        return javaArray;
    } else if (String.class.equals(type)) {
        return (String) value;
    }
    return null;
}

From source file:org.openengsb.persistence.connector.jpabackend.ConnectorPropertiesWrapperJPAEntity.java

@SuppressWarnings("unchecked")
public static ConnectorPropertiesWrapperJPAEntity getFromObject(Object property) {
    Class<?> clazz = property.getClass();

    ConnectorPropertiesWrapperJPAEntity wrapper = new ConnectorPropertiesWrapperJPAEntity();

    List<ConnectorPropertyJPAEntity> propList = new ArrayList<ConnectorPropertyJPAEntity>();
    wrapper.setProperties(propList);//from w ww .  ja  va 2s  .c om
    wrapper.setCollectionType(clazz.getName());

    if (clazz.isArray()) {
        Object[] arr;
        Class<?> compClass = clazz.getComponentType();
        if (compClass.isPrimitive()) {
            compClass = ClassUtils.primitiveToWrapper(compClass);
            int length = Array.getLength(property);
            Object wrapperArray = Array.newInstance(compClass, length);
            for (int i = 0; i < length; i++) {
                Array.set(wrapperArray, i, Array.get(property, i));
            }
            arr = (Object[]) wrapperArray;
        } else {
            arr = (Object[]) property;
        }
        loopProperties(Arrays.asList(arr), propList);
        return wrapper;
    } else {
        if (Collection.class.isAssignableFrom(clazz)) {
            Collection<Object> coll = (Collection<Object>) property;
            loopProperties(coll, propList);
            return wrapper;
        } else {
            wrapper.setCollectionType(null);
            propList.add(ConnectorPropertyJPAEntity.getFromObject(property));
            return wrapper;
        }
    }
}

From source file:com.laxser.blitz.lama.core.SelectOperation.java

@Override
public Object execute(Map<String, Object> parameters) {
    // /* w w  w .j a va  2  s .  co m*/
    List<?> listResult = dataAccess.select(sql, modifier, parameters, rowMapper);
    final int sizeResult = listResult.size();

    //  Result ?
    if (returnType.isAssignableFrom(List.class)) {

        //   List ?
        return listResult;

    } else if (returnType.isArray() && byte[].class != returnType) {
        Object array = Array.newInstance(returnType.getComponentType(), sizeResult);
        if (returnType.getComponentType().isPrimitive()) {
            int len = listResult.size();
            for (int i = 0; i < len; i++) {
                Array.set(array, i, listResult.get(i));
            }
        } else {
            listResult.toArray((Object[]) array);
        }
        return array;

    } else if (Map.class.isAssignableFrom(returnType)) {
        //   KeyValuePair ??  Map 
        // entry.key?nullHashMap
        Map<Object, Object> map;
        if (returnType.isAssignableFrom(HashMap.class)) {

            map = new HashMap<Object, Object>(listResult.size() * 2);

        } else if (returnType.isAssignableFrom(Hashtable.class)) {

            map = new Hashtable<Object, Object>(listResult.size() * 2);

        } else {

            throw new Error(returnType.toString());
        }
        for (Object obj : listResult) {
            if (obj == null) {
                continue;
            }

            Map.Entry<?, ?> entry = (Map.Entry<?, ?>) obj;

            if (map.getClass() == Hashtable.class && entry.getKey() == null) {
                continue;
            }

            map.put(entry.getKey(), entry.getValue());
        }

        return map;

    } else if (returnType.isAssignableFrom(HashSet.class)) {

        //   Set ?
        return new HashSet<Object>(listResult);

    } else {

        if (sizeResult == 1) {
            // ?  Bean?Boolean
            return listResult.get(0);

        } else if (sizeResult == 0) {

            // null
            if (returnType.isPrimitive()) {
                String msg = "Incorrect result size: expected 1, actual " + sizeResult + ": "
                        + modifier.toString();
                throw new EmptyResultDataAccessException(msg, 1);
            } else {
                return null;
            }

        } else {
            // IncorrectResultSizeDataAccessException
            String msg = "Incorrect result size: expected 0 or 1, actual " + sizeResult + ": "
                    + modifier.toString();
            throw new IncorrectResultSizeDataAccessException(msg, 1, sizeResult);
        }
    }
}

From source file:Main.java

/**
 * Underlying implementation of add(array, index, element) methods. 
 * The last parameter is the class, which may not equal element.getClass 
 * for primitives./*w  ww  .j a v a2s.  c  om*/
 *
 * @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
 * @param clss the type of the element being added
 * @return A new array containing the existing elements and the new element
 */
private static Object add(Object array, int index, Object element, Class clss) {
    if (array == null) {
        if (index != 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
        }
        Object joinedArray = Array.newInstance(clss, 1);
        Array.set(joinedArray, 0, element);
        return joinedArray;
    }
    int length = Array.getLength(array);
    if (index > length || index < 0) {
        throw new IndexOutOfBoundsException("Index: " + index + ", Length: " + length);
    }
    Object result = Array.newInstance(clss, 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 result;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.parser.ext.factory.base.ArrayObjectDescription.java

/**
 * Creates an object based on the description.
 *
 * @return The object./*from ww w  .j  a v a  2s .  c o  m*/
 */
public Object createObject() {
    try {
        final Integer size = (Integer) getParameter("size");
        if (size == null) {
            final ArrayList l = new ArrayList();
            int counter = 0;
            while (getParameterDefinition(String.valueOf(counter)) != null) {
                final Object value = getParameter(String.valueOf(counter));
                if (value == null) {
                    break;
                }

                l.add(value);
                counter += 1;
            }

            final Object o = Array.newInstance(getObjectClass().getComponentType(), l.size());
            for (int i = 0; i < l.size(); i++) {
                Array.set(o, i, l.get(i));
            }
            return o;
        } else {
            // a size is given, so we can assume that all values are defined.
            final Object o = Array.newInstance(getObjectClass().getComponentType(), size.intValue());
            for (int i = 0; i < size.intValue(); i++) {
                Array.set(o, i, getParameter(String.valueOf(i)));
            }
            return o;
        }
    } catch (Exception ie) {
        ArrayObjectDescription.logger.warn("Unable to instantiate Object", ie);
        return null;
    }
}

From source file:org.kordamp.ezmorph.array.ObjectArrayMorpher.java

public Object morph(Object array) {
    if (array == null) {
        return null;
    }// www . j  av a  2  s  .  c  o m

    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        int dims = getDimensions(array.getClass());
        int[] dimensions = createDimensions(dims, length);
        Object result = Array.newInstance(this.target, dimensions);

        if (dims == 1) {
            for (int index = 0; index < length; index++) {
                try {
                    Object value = Array.get(array, index);
                    if (value != null && !morpher.supports(value.getClass())) {
                        throw new MorphException(value.getClass() + " is not supported");
                    }
                    Object morphed = morphMethod.invoke(morpher, value);
                    Array.set(result, index, morphed);
                } catch (MorphException me) {
                    throw me;
                } catch (Exception e) {
                    throw new MorphException(e);
                }
            }
        } else {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, morph(Array.get(array, index)));
            }
        }

        return result;
    } else {
        throw new MorphException("argument is not an array: " + array.getClass());
    }
}

From source file:test.be.fedict.eid.applet.Pkcs15Test.java

public static <T> T parsePkcs15File(byte[] data, Class<T> type)
        throws InstantiationException, IllegalAccessException {
    T result = type.newInstance();//from w  w w  . j av a 2 s  .c  om
    int dataIdx = 0;
    Tag tagAnnotation = type.getAnnotation(Tag.class);
    if (null != tagAnnotation) {
        byte tag = tagAnnotation.value();
        if (tag != data[0]) {
            throw new RuntimeException("incorrect tag: " + Integer.toHexString(tag));
        }
        dataIdx++;
        int size = data[1];
        dataIdx++;
        LOG.debug("size: " + size);
        if (data.length - dataIdx != size) {
            throw new RuntimeException("data size incorrect: " + size + " for tag " + Integer.toHexString(tag));
        }
    }
    Field[] fields = type.getDeclaredFields();
    if (1 == fields.length) {
        Field field = fields[0];
        if (field.getType().isArray()) {
            Class<?> componentType = field.getType().getComponentType();
            Object component = parsePkcs15File(data, componentType);
            Object array = Array.newInstance(componentType, 1);
            Array.set(array, 0, component);
            field.set(result, array);
            return result;
        }
    }
    while (dataIdx < data.length) {
        byte tag = data[dataIdx];
        dataIdx++;
        int size = data[dataIdx];
        dataIdx++;
        LOG.debug("tag: " + Integer.toHexString(tag) + "; size: " + size);
        for (Field field : fields) {
            Tag fieldTagAnnotation = field.getAnnotation(Tag.class);
            if (null != fieldTagAnnotation) {
                byte fieldTag = fieldTagAnnotation.value();
                if (fieldTag == tag) {
                    LOG.debug("field found for tag " + Integer.toHexString(tag) + ": " + field.getName());
                    Object value;
                    if (String.class.equals(field.getType())) {
                        value = new String(Arrays.copyOfRange(data, dataIdx, dataIdx + size));
                    } else if (byte[].class.equals(field.getType())) {
                        value = Arrays.copyOfRange(data, dataIdx, dataIdx + size);
                    } else {
                        throw new RuntimeException("unsupported field type: " + field.getType().getName()
                                + " for field " + field.getName());
                    }
                    field.set(result, value);
                }
            }
        }
        dataIdx += size;
    }
    return result;
}

From source file:ArrayUtils.java

/**
 * Inserts an element into the array--for primitive types
 * //from   ww w  .j  ava 2 s  . c  o  m
 * @param anArray
 *            The array to insert into
 * @param anElement
 *            The element to insert
 * @param anIndex
 *            The index for the new element
 * @return The new array with all elements of <code>anArray</code>, but with
 *         <code>anElement</code> inserted at index <code>anIndex</code>
 */
public static Object addP(Object anArray, Object anElement, int anIndex) {
    Object ret;
    int length;
    if (anArray == null) {
        if (anIndex != 0)
            throw new ArrayIndexOutOfBoundsException("Cannot set " + anIndex + " element in a null array");
        ret = Array.newInstance(anElement.getClass(), 1);
        Array.set(ret, 0, anElement);
        return ret;
    } else {
        length = Array.getLength(anArray);
        ret = Array.newInstance(anArray.getClass().getComponentType(), length + 1);
    }
    System.arraycopy(anArray, 0, ret, 0, anIndex);
    put(ret, anElement, anIndex);
    System.arraycopy(anArray, anIndex, ret, anIndex + 1, length - anIndex);
    return ret;
}

From source file:org.kordamp.ezmorph.array.ByteArrayMorpher.java

public Object morph(Object array) {
    if (array == null) {
        return null;
    }/*  www. j  a  v a2s.  c  o m*/

    if (BYTE_ARRAY_CLASS.isAssignableFrom(array.getClass())) {
        // no conversion needed
        return (byte[]) array;
    }

    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        int dims = getDimensions(array.getClass());
        int[] dimensions = createDimensions(dims, length);
        Object result = Array.newInstance(byte.class, dimensions);
        ByteMorpher morpher = isUseDefault() ? new ByteMorpher(defaultValue) : new ByteMorpher();
        if (dims == 1) {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, morpher.morph(Array.get(array, index)));
            }
        } else {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, morph(Array.get(array, index)));
            }
        }
        return result;
    } else {
        throw new MorphException("argument is not an array: " + array.getClass());
    }
}

From source file:org.openTwoFactor.clientExt.net.sf.ezmorph.array.ObjectArrayMorpher.java

public Object morph(Object array) {
    if (array == null) {
        return null;
    }//from  www  .  j  a  va 2  s.  c o m

    if (array.getClass().isArray()) {
        int length = Array.getLength(array);
        int dims = getDimensions(array.getClass());
        int[] dimensions = createDimensions(dims, length);
        Object result = Array.newInstance(this.target, dimensions);

        if (dims == 1) {
            for (int index = 0; index < length; index++) {
                try {
                    Object value = Array.get(array, index);
                    if (value != null && !morpher.supports(value.getClass())) {
                        throw new MorphException(value.getClass() + " is not supported");
                    }
                    Object morphed = morphMethod.invoke(morpher, new Object[] { value });
                    Array.set(result, index, morphed);
                } catch (MorphException me) {
                    throw me;
                } catch (Exception e) {
                    throw new MorphException(e);
                }
            }
        } else {
            for (int index = 0; index < length; index++) {
                Array.set(result, index, morph(Array.get(array, index)));
            }
        }

        return result;
    } else {
        throw new MorphException("argument is not an array: " + array.getClass());
    }
}