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:com.espertech.esper.epl.core.SelectExprInsertEventBean.java

private void initializeSetterManufactor(boolean isUsingWildcard, StreamTypeService typeService,
        ExprEvaluator[] expressionNodes, String[] columnNames, Object[] expressionReturnTypes,
        MethodResolutionService methodResolutionService, EventAdapterService eventAdapterService)
        throws ExprValidationException {
    List<WriteablePropertyDescriptor> writablePropertiesList = new ArrayList<WriteablePropertyDescriptor>();
    List<ExprEvaluator> evaluatorsList = new ArrayList<ExprEvaluator>();
    List<TypeWidener> widenersList = new ArrayList<TypeWidener>();

    // loop over all columns selected, if any
    for (int i = 0; i < columnNames.length; i++) {
        WriteablePropertyDescriptor selectedWritable = null;
        TypeWidener widener = null;//from w  w w . ja va2  s  .  c om
        ExprEvaluator evaluator = expressionNodes[i];

        for (WriteablePropertyDescriptor desc : writables) {
            if (!desc.getPropertyName().equals(columnNames[i])) {
                continue;
            }

            Object columnType = expressionReturnTypes[i];
            if (columnType == null) {
                TypeWidenerFactory.getCheckPropertyAssignType(columnNames[i], null, desc.getType(),
                        desc.getPropertyName());
            } else if (columnType instanceof EventType) {
                EventType columnEventType = (EventType) columnType;
                final Class returnType = columnEventType.getUnderlyingType();
                widener = TypeWidenerFactory.getCheckPropertyAssignType(columnNames[i],
                        columnEventType.getUnderlyingType(), desc.getType(), desc.getPropertyName());
                int streamNum = 0;
                for (int j = 0; j < typeService.getEventTypes().length; j++) {
                    if (typeService.getEventTypes()[j] == columnEventType) {
                        streamNum = j;
                        break;
                    }
                }
                final int streamNumEval = streamNum;
                evaluator = new ExprEvaluator() {
                    public Object evaluate(EventBean[] eventsPerStream, boolean isNewData,
                            ExprEvaluatorContext exprEvaluatorContext) {
                        EventBean event = eventsPerStream[streamNumEval];
                        if (event != null) {
                            return event.getUnderlying();
                        }
                        return null;
                    }

                    public Class getType() {
                        return returnType;
                    }

                    public Map<String, Object> getEventType() {
                        return null;
                    }
                };
            }
            // handle case where the select-clause contains an fragment array
            else if (columnType instanceof EventType[]) {
                EventType columnEventType = ((EventType[]) columnType)[0];
                final Class componentReturnType = columnEventType.getUnderlyingType();
                final Class arrayReturnType = Array.newInstance(componentReturnType, 0).getClass();

                widener = TypeWidenerFactory.getCheckPropertyAssignType(columnNames[i], arrayReturnType,
                        desc.getType(), desc.getPropertyName());
                final ExprEvaluator inner = evaluator;
                evaluator = new ExprEvaluator() {
                    public Object evaluate(EventBean[] eventsPerStream, boolean isNewData,
                            ExprEvaluatorContext exprEvaluatorContext) {
                        Object result = inner.evaluate(eventsPerStream, isNewData, exprEvaluatorContext);
                        if (!(result instanceof EventBean[])) {
                            return null;
                        }
                        EventBean[] events = (EventBean[]) result;
                        Object values = Array.newInstance(componentReturnType, events.length);
                        for (int i = 0; i < events.length; i++) {
                            Array.set(values, i, events[i].getUnderlying());
                        }
                        return values;
                    }

                    public Class getType() {
                        return componentReturnType;
                    }

                    public Map<String, Object> getEventType() {
                        return null;
                    }
                };
            } else if (!(columnType instanceof Class)) {
                String message = "Invalid assignment of column '" + columnNames[i] + "' of type '" + columnType
                        + "' to event property '" + desc.getPropertyName() + "' typed as '"
                        + desc.getType().getName() + "', column and parameter types mismatch";
                throw new ExprValidationException(message);
            } else {
                widener = TypeWidenerFactory.getCheckPropertyAssignType(columnNames[i], (Class) columnType,
                        desc.getType(), desc.getPropertyName());
            }

            selectedWritable = desc;
            break;
        }

        if (selectedWritable == null) {
            String message = "Column '" + columnNames[i]
                    + "' could not be assigned to any of the properties of the underlying type (missing column names, event property, setter method or constructor?)";
            throw new ExprValidationException(message);
        }

        // add
        writablePropertiesList.add(selectedWritable);
        evaluatorsList.add(evaluator);
        widenersList.add(widener);
    }

    // handle wildcard
    if (isUsingWildcard) {
        EventType sourceType = typeService.getEventTypes()[0];
        for (EventPropertyDescriptor eventPropDescriptor : sourceType.getPropertyDescriptors()) {
            if (eventPropDescriptor.isRequiresIndex() || (eventPropDescriptor.isRequiresMapkey())) {
                continue;
            }

            WriteablePropertyDescriptor selectedWritable = null;
            TypeWidener widener = null;
            ExprEvaluator evaluator = null;

            for (WriteablePropertyDescriptor writableDesc : writables) {
                if (!writableDesc.getPropertyName().equals(eventPropDescriptor.getPropertyName())) {
                    continue;
                }

                widener = TypeWidenerFactory.getCheckPropertyAssignType(eventPropDescriptor.getPropertyName(),
                        eventPropDescriptor.getPropertyType(), writableDesc.getType(),
                        writableDesc.getPropertyName());
                selectedWritable = writableDesc;

                final String propertyName = eventPropDescriptor.getPropertyName();
                final Class propertyType = eventPropDescriptor.getPropertyType();
                evaluator = new ExprEvaluator() {

                    public Object evaluate(EventBean[] eventsPerStream, boolean isNewData,
                            ExprEvaluatorContext exprEvaluatorContext) {
                        EventBean event = eventsPerStream[0];
                        if (event != null) {
                            return event.get(propertyName);
                        }
                        return null;
                    }

                    public Class getType() {
                        return propertyType;
                    }

                    public Map<String, Object> getEventType() {
                        return null;
                    }
                };
                break;
            }

            if (selectedWritable == null) {
                String message = "Event property '" + eventPropDescriptor.getPropertyName()
                        + "' could not be assigned to any of the properties of the underlying type (missing column names, event property, setter method or constructor?)";
                throw new ExprValidationException(message);
            }

            writablePropertiesList.add(selectedWritable);
            evaluatorsList.add(evaluator);
            widenersList.add(widener);
        }
    }

    // assign
    this.writableProperties = writablePropertiesList
            .toArray(new WriteablePropertyDescriptor[writablePropertiesList.size()]);
    this.exprEvaluators = evaluatorsList.toArray(new ExprEvaluator[evaluatorsList.size()]);
    this.wideners = widenersList.toArray(new TypeWidener[widenersList.size()]);

    try {
        eventManufacturer = eventAdapterService.getManufacturer(eventType, writableProperties,
                methodResolutionService);
    } catch (EventBeanManufactureException e) {
        throw new ExprValidationException(e.getMessage(), e);
    }
}

From source file:kx.c.java

public static Object[] autoboxArray(Object data) {
    if (data.getClass().isArray()) {
        Object[] dstArray = new Object[Array.getLength(data)];
        for (int row = 0; row < Array.getLength(data); row++) {
            Object o = Array.get(data, row);
            if (o == null) {
                o = "::";
            }//  w w  w . ja v  a  2s.  co  m
            if (o instanceof char[]) {
                // char arrays are strings...
                o = new String((char[]) o);
            } else if (o.getClass().isArray()) {
                o = autoboxArray(o);
            }
            Array.set(dstArray, row, o);

        }
        return dstArray;
    }
    throw new IncompleteArgumentException("data was not an array");
}

From source file:org.romaframework.core.schema.SchemaHelper.java

public static void insertElements(SchemaField iField, Object iContent, Object[] iSelection,
        boolean overrideContent) {
    if (iField == null) {
        log.warn("[SchemaHelper.insertElements] Field is null");
        return;//from www  .  j  a  v  a 2  s.  c  o m
    }
    if (iContent == null) {
        log.warn("[SchemaHelper.insertElements] target object is null. Cannot to value field " + iField);
        return;
    }
    boolean simpleSet = false;
    if (iSelection != null && iSelection.length > 0 && iSelection[0] != null)
        simpleSet = Roma.schema().getSchemaClass(iSelection[0]).equals(iField.getType().getSchemaClass());
    // TODO: REVIEW BIND MODE WITH NESTED FIELDS EXPRESSION
    Object currentValue = SchemaHelper.getFieldValue(iField, iContent);

    if (currentValue == null && SchemaHelper.isMultiValueObject(iField) && !simpleSet)
        // CHECK IF IT'S A COLLECTION: IN THIS CASE THROW AN EXCEPTION SINCE
        // IT MUST BE INITIALIZED BEFORE TO USE IT
        if (isAssignableAs(iField.getType(), Collection.class))
            throw new IllegalArgumentException(
                    "The collection in field '" + iField.getEntity().getSchemaClass().getName() + "."
                            + iField.getName() + "' is null: cannot add elements. Remember to initialize it.");
        else if (isAssignableAs(iField.getType(), Map.class))
            throw new IllegalArgumentException(
                    "The map in field '" + iField.getEntity().getSchemaClass().getName() + "."
                            + iField.getName() + "' is null: cannot add elements. Remember to initialize it.");

    if (currentValue instanceof Collection<?> && !simpleSet) {
        // INSERT EACH ELEMENT OF SELECTION IN THE COLLECTION
        Collection<Object> coll = (Collection<Object>) currentValue;
        if (overrideContent)
            coll.clear();
        if (iSelection != null) {
            for (Object o : iSelection) {
                coll.add(EntityHelper.getEntityObjectIfNeeded(o, iField.getEmbeddedType()));
            }
        }
    } else if (currentValue instanceof Map && !simpleSet) {
        // INSERT EACH ELEMENT OF SELECTION IN THE MAP (KEY = SELECTION
        // OBJ.toString()
        if (overrideContent)
            ((Map<String, Object>) currentValue).clear();
        if (iSelection != null) {
            for (Object o : iSelection) {
                ((Map<String, Object>) currentValue).put(EntityHelper.getEntityObject(o).toString(),
                        EntityHelper.getEntityObject(o));
            }
        }
    } else if (((Class<?>) iField.getLanguageType()).isArray() && !simpleSet) {
        Object array = null;
        if (iField.getLanguageType().equals(Object[].class)) {
            // OBJECT[]: NO CONVERSION REQUIRED
            if (overrideContent) {
                array = iSelection;
            } else {
                Object[] oldValue = (Object[]) SchemaHelper.getFieldValue(iField, iContent);
                int oldLength = 0;
                if (oldValue != null)
                    oldLength = oldValue.length;
                array = new Object[oldLength + iSelection.length];
                if (oldValue != null)
                    System.arraycopy(oldValue, 0, array, 0, oldLength);
                System.arraycopy(iSelection, 0, array, oldLength, iSelection.length);
            }
        } else if (iSelection != null) {
            // COPY THE ARRAY TO USE REAL CLASS ARRAY, IF ANY
            int i = 0;
            Object oldValue = SchemaHelper.getFieldValue(iField, iContent);
            if (overrideContent || oldValue == null) {
                array = Array.newInstance(((Class<?>) iField.getLanguageType()).getComponentType(),
                        iSelection.length);
            } else {
                int oldSize = Array.getLength(oldValue);
                array = Array.newInstance(((Class<?>) iField.getLanguageType()).getComponentType(),
                        iSelection.length + oldSize);
                for (; i < oldSize; ++i) {
                    Array.set(array, i, Array.get(oldValue, i));
                }
            }

            for (int sourcePos = 0; sourcePos < iSelection.length; ++sourcePos, ++i) {
                Array.set(array, i, iSelection[sourcePos]);
            }
        }
        SchemaHelper.setFieldValue(iField, iContent, array);
    } else {
        Object firstSelection = iSelection != null && iSelection.length > 0 ? iSelection[0] : null;
        SchemaHelper.setFieldValue(iField, iContent,
                EntityHelper.getEntityObjectIfNeeded(firstSelection, iField.getType()));
    }

    // REFRESH THE FIELD
    Roma.fieldChanged(iContent, iField.getName());
}

From source file:io.s4.util.LoadGenerator.java

@SuppressWarnings("unchecked")
public Object makeArray(Property property, JSONArray jsonArray) {
    Property componentProperty = property.getComponentProperty();
    Class clazz = componentProperty.getType();

    int size = jsonArray.length();

    Object array = Array.newInstance(clazz, size);

    try {/*from  w w w.j a v a2s  .co m*/
        for (int i = 0; i < size; i++) {
            Object value = jsonArray.get(i);
            Object adjustedValue = makeSettableValue(componentProperty, value);
            Array.set(array, i, adjustedValue);
        }
    } catch (JSONException je) {
        throw new RuntimeException(je);
    }
    return array;
}

From source file:javadz.beanutils.LazyDynaBean.java

/**
 * Set the value of an indexed property with the specified name.
 *
 * @param name Name of the property whose value is to be set
 * @param index Index of the property to be set
 * @param value Value to which this property is to be set
 *
 * @exception ConversionException if the specified value cannot be
 *  converted to the type required for this property
 * @exception IllegalArgumentException if there is no property
 *  of the specified name//w w  w  .j  a v  a 2  s  .  co m
 * @exception IllegalArgumentException if the specified property
 *  exists, but is not indexed
 * @exception IndexOutOfBoundsException if the specified index
 *  is outside the range of the underlying property
 */
public void set(String name, int index, Object value) {

    // If its not a property, then create default indexed property
    if (!isDynaProperty(name)) {
        set(name, defaultIndexedProperty(name));
    }

    // Get the indexed property
    Object indexedProperty = get(name);

    // Check that the property is indexed
    if (!dynaClass.getDynaProperty(name).isIndexed()) {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'"
                + dynaClass.getDynaProperty(name).getType().getName());
    }

    // Grow indexed property to appropriate size
    indexedProperty = growIndexedProperty(name, indexedProperty, index);

    // Set the value in an array
    if (indexedProperty.getClass().isArray()) {
        Array.set(indexedProperty, index, value);
    } else if (indexedProperty instanceof List) {
        ((List) indexedProperty).set(index, value);
    } else {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]' "
                + indexedProperty.getClass().getName());
    }

}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static Object readObjectFromXml(Element node) throws Exception {
    String nodeName = node.getNodeName();
    String nodeValue = ((Element) node).getAttribute("value");

    if (nodeName.equals("java.lang.Boolean")) {
        return new Boolean(nodeValue);
    } else if (nodeName.equals("java.lang.Byte")) {
        return new Byte(nodeValue);
    } else if (nodeName.equals("java.lang.Character")) {
        return new Character(nodeValue.charAt(0));
    } else if (nodeName.equals("java.lang.Integer")) {
        return new Integer(nodeValue);
    } else if (nodeName.equals("java.lang.Double")) {
        return new Double(nodeValue);
    } else if (nodeName.equals("java.lang.Float")) {
        return new Float(nodeValue);
    } else if (nodeName.equals("java.lang.Long")) {
        return new Long(nodeValue);
    } else if (nodeName.equals("java.lang.Short")) {
        return new Short(nodeValue);
    } else if (nodeName.equals("java.lang.String")) {
        return nodeValue;
    } else if (nodeName.equals("array")) {
        String className = node.getAttribute("classname");
        String length = node.getAttribute("length");
        int len = (new Integer(length)).intValue();

        Object array;/*from  w  w w.j  a  v  a 2  s . co  m*/
        if (className.equals("byte")) {
            array = new byte[len];
        } else if (className.equals("boolean")) {
            array = new boolean[len];
        } else if (className.equals("char")) {
            array = new char[len];
        } else if (className.equals("double")) {
            array = new double[len];
        } else if (className.equals("float")) {
            array = new float[len];
        } else if (className.equals("int")) {
            array = new int[len];
        } else if (className.equals("long")) {
            array = new long[len];
        } else if (className.equals("short")) {
            array = new short[len];
        } else {
            array = Array.newInstance(Class.forName(className), len);
        }

        Node xmlNode = null;
        NodeList nl = node.getChildNodes();
        int len_nl = nl.getLength();
        int i = 0;
        for (int j = 0; j < len_nl; j++) {
            xmlNode = nl.item(j);
            if (xmlNode.getNodeType() == Node.ELEMENT_NODE) {
                Object o = XMLUtils.readObjectFromXml((Element) xmlNode);
                Array.set(array, i, o);
                i++;
            }
        }

        return array;
    }
    // XMLization
    else if (nodeName.equals("xmlizable")) {
        String className = node.getAttribute("classname");

        Node xmlNode = findChildNode(node, Node.ELEMENT_NODE);
        Object xmlizable = Class.forName(className).newInstance();
        ((XMLizable) xmlizable).readXml(xmlNode);

        return xmlizable;
    }
    // Serialization
    else if (nodeName.equals("serializable")) {
        Node cdata = findChildNode(node, Node.CDATA_SECTION_NODE);
        String objectSerializationData = cdata.getNodeValue();
        Engine.logEngine.debug("Object serialization data:\n" + objectSerializationData);
        byte[] objectBytes = org.apache.commons.codec.binary.Base64.decodeBase64(objectSerializationData);

        // We read the object to a bytes array
        ByteArrayInputStream inputStream = new ByteArrayInputStream(objectBytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        Object object = objectInputStream.readObject();
        inputStream.close();

        return object;
    }

    return null;
}

From source file:org.apache.openjpa.kernel.AttachStrategy.java

/**
 * Returns an attached version of the <code>frma</code>
 * array if it is different than <code>toa</code>. If the arrays
 * will be identical, returns <code>toa</code>.
 *///from w  ww .  j av a2  s.co  m
private Object replaceArray(AttachManager manager, Object frma, Object toa, OpenJPAStateManager sm,
        FieldMetaData fmd) {
    int len = Array.getLength(frma);
    boolean diff = toa == null || len != Array.getLength(toa);

    // populate an array copy on the initial assumption that the array
    // is dirty
    Object newa = Array.newInstance(fmd.getElement().getDeclaredType(), len);
    ValueMetaData vmd = fmd.getElement();
    boolean pc = vmd.isDeclaredTypePC();
    Object elem;
    for (int i = 0; i < len; i++) {
        elem = Array.get(frma, i);
        if (pc) {
            if (vmd.getCascadeAttach() == ValueMetaData.CASCADE_NONE)
                elem = getReference(manager, elem, sm, vmd);
            else
                elem = manager.attach(elem, null, sm, vmd, false);
        }
        diff = diff || !equals(elem, Array.get(toa, i), pc);
        Array.set(newa, i, elem);
    }
    return (diff) ? newa : toa;
}

From source file:org.enerj.apache.commons.beanutils.LazyDynaBean.java

protected Object growIndexedProperty(String name, Object indexedProperty, int index) {

    // Grow a List to the appropriate size
    if (indexedProperty instanceof List) {

        List list = (List) indexedProperty;
        while (index >= list.size()) {
            list.add(null);/*from   w w w.  j a  va  2  s.  c o  m*/
        }

    }

    // Grow an Array to the appropriate size
    if ((indexedProperty.getClass().isArray())) {

        int length = Array.getLength(indexedProperty);
        if (index >= length) {
            Class componentType = indexedProperty.getClass().getComponentType();
            Object newArray = Array.newInstance(componentType, (index + 1));
            System.arraycopy(indexedProperty, 0, newArray, 0, length);
            indexedProperty = newArray;
            set(name, indexedProperty);
            int newLength = Array.getLength(indexedProperty);
            for (int i = length; i < newLength; i++) {
                Array.set(indexedProperty, i, createProperty(name + "[" + i + "]", componentType));
            }
        }
    }

    return indexedProperty;

}

From source file:org.tinygroup.weblayer.webcontext.parser.util.BeanWrapperImpl.java

private Object newValue(Class<?> type, String name) {
    try {/*from  w  w w  . j a v  a 2s . com*/
        if (type.isArray()) {
            Class<?> componentType = type.getComponentType();
            // - only handles 2-dimensional arrays
            if (componentType.isArray()) {
                Object array = Array.newInstance(componentType, 1);
                Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
                return array;
            } else {
                return Array.newInstance(componentType, 0);
            }
        } else if (Collection.class.isAssignableFrom(type)) {
            return CollectionFactory.createCollection(type, 16);
        } else if (Map.class.isAssignableFrom(type)) {
            return CollectionFactory.createMap(type, 16);
        } else {
            return type.newInstance();
        }
    } catch (Exception ex) {
        throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
                "Could not instantiate property type [" + type.getName()
                        + "] to auto-grow nested property path: " + ex);
    }
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

private Object convertToTypedArray(Object input, String propertyName, Class<?> componentType) {
    if (input instanceof Collection) {
        // Convert Collection elements to array elements.
        Collection coll = (Collection) input;
        Object result = Array.newInstance(componentType, coll.size());
        int i = 0;
        for (Iterator it = coll.iterator(); it.hasNext(); i++) {
            Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, i), null, it.next(),
                    componentType);//from   w w w  .  jav  a  2s. co m
            Array.set(result, i, value);
        }
        return result;
    } else if (input.getClass().isArray()) {
        // Convert array elements, if necessary.
        if (componentType.equals(input.getClass().getComponentType())
                && !this.propertyEditorRegistry.hasCustomEditorForElement(componentType, propertyName)) {
            return input;
        }
        int arrayLength = Array.getLength(input);
        Object result = Array.newInstance(componentType, arrayLength);
        for (int i = 0; i < arrayLength; i++) {
            Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, i), null,
                    Array.get(input, i), componentType);
            Array.set(result, i, value);
        }
        return result;
    } else {
        // A plain value: convert it to an array with a single component.
        Object result = Array.newInstance(componentType, 1);
        Object value = convertIfNecessary(buildIndexedPropertyName(propertyName, 0), null, input,
                componentType);
        Array.set(result, 0, value);
        return result;
    }
}