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.primeframework.mvc.parameter.convert.AbstractGlobalConverter.java

/**
 * This performs the conversion from a single String value to an array of the given type.
 *
 * @param value             The value to convert to an array.
 * @param convertTo         The array type to convert to.
 * @param dynamicAttributes The dynamic attributes used to assist in conversion.
 * @param expression        The full path to the expression that is causing the conversion.
 * @return The converted value.//from  w  w w  . ja v  a 2 s. c om
 * @throws ConversionException     If the conversion failed.
 * @throws ConverterStateException if the converter didn't have all of the information it needed to perform the
 *                                 conversion.
 */
protected Object stringToArray(String value, Type convertTo, Map<String, String> dynamicAttributes,
        String expression) throws ConversionException {
    if (value == null) {
        return null;
    }

    Object finalArray;
    Class<?> rawType = TypeTools.rawType(convertTo);
    if (StringUtils.isBlank(value)) {
        finalArray = Array.newInstance(rawType.getComponentType(), 0);
    } else {
        String[] parts = value.split(",");
        finalArray = Array.newInstance(rawType.getComponentType(), parts.length);
        for (int i = 0; i < parts.length; i++) {
            Object singleValue = stringToObject(parts[i], rawType.getComponentType(), dynamicAttributes,
                    expression);
            Array.set(finalArray, i, singleValue);
        }
    }

    return finalArray;
}

From source file:com.cisco.oss.foundation.monitoring.ServerInfo.java

@SuppressWarnings("unchecked")
private static Object getChild(Object obj, String attributeName, Object value, boolean isSet)
        throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
        InvocationTargetException {
    int substrstart = attributeName.indexOf('[');
    int substrend = attributeName.indexOf(']');

    if (substrstart == -1) {
        if (isSet) {
            String strFunc = "set" + attributeName;
            callSetMethod(obj, value, strFunc);
            return null;
        } else {//  w w w. j  av a 2  s .  c  om
            String getStr = "get";
            StringBuilder strBuild = new StringBuilder(attributeName);
            strBuild.insert(0, getStr);

            String getFuncStr = strBuild.toString();

            Method m = obj.getClass().getMethod(getFuncStr);
            Object result = m.invoke(obj);

            return result;
        }
    } else {
        String firststr = attributeName.substring(0, substrstart);
        String secondstr = attributeName.substring(substrstart + 1, substrend);
        Object parentObj = obj;
        Object requests = parentObj.getClass().getDeclaredMethod("get" + firststr, new Class[] {})
                .invoke(parentObj, new Object[] {});

        if (requests instanceof Map) {
            Object result = ((HashMap) requests).get(secondstr);
            return result;
        } else if (requests instanceof List) {
            if (isSet) {
                ((List) requests).set(Integer.parseInt(secondstr), value);
                return null;
            } else {
                Object request = ((List) requests).get(Integer.parseInt(secondstr));
                return request;
            }
        } else if (requests.getClass().isArray()) {
            if (isSet) {
                Object[] arr = (Object[]) requests;
                Array.set(arr, Integer.parseInt(secondstr), value);
                return null;
            } else {
                Object[] arr = (Object[]) requests;
                return Array.get(arr, Integer.parseInt(secondstr));
            }
        } else {
            return null;
        }
    }
}

From source file:org.apache.myfaces.shared_impl.renderkit._SharedRendererUtils.java

static Object getConvertedUISelectManyValue(FacesContext facesContext, UISelectMany component,
        String[] submittedValue) throws ConverterException {
    // Attention!
    // This code is duplicated in jsfapi component package.
    // If you change something here please do the same in the other class!

    if (submittedValue == null)
        throw new NullPointerException("submittedValue");

    ValueBinding vb = component.getValueBinding("value");
    Class valueType = null;/*from   w  w w .  j  a v a2  s.c o m*/
    Class arrayComponentType = null;
    if (vb != null) {
        valueType = vb.getType(facesContext);
        if (valueType != null && valueType.isArray()) {
            arrayComponentType = valueType.getComponentType();
        }
    }

    Converter converter = component.getConverter();
    if (converter == null) {
        if (valueType == null) {
            // No converter, and no idea of expected type
            // --> return the submitted String array
            return submittedValue;
        }

        if (List.class.isAssignableFrom(valueType)) {
            // expected type is a List
            // --> according to javadoc of UISelectMany we assume that the element type
            //     is java.lang.String, and copy the String array to a new List
            int len = submittedValue.length;
            List lst = new ArrayList(len);
            for (int i = 0; i < len; i++) {
                lst.add(submittedValue[i]);
            }
            return lst;
        }

        if (arrayComponentType == null) {
            throw new IllegalArgumentException("ValueBinding for UISelectMany must be of type List or Array");
        }

        if (String.class.equals(arrayComponentType))
            return submittedValue; //No conversion needed for String type
        if (Object.class.equals(arrayComponentType))
            return submittedValue; //No conversion for Object class

        try {
            converter = facesContext.getApplication().createConverter(arrayComponentType);
        } catch (FacesException e) {
            log(facesContext, "No Converter for type " + arrayComponentType.getName() + " found", e);
            return submittedValue;
        }
        if (converter == null) {
            log(facesContext, "No Converter for type " + arrayComponentType.getName() + " found.", null);
            return submittedValue;
        }
    }

    // Now, we have a converter...
    // We determine the type of the component array after converting one of it's elements
    if (vb != null) {
        valueType = vb.getType(facesContext);
        if (valueType != null && valueType.isArray()) {
            if (submittedValue.length > 0) {
                arrayComponentType = converter.getAsObject(facesContext, component, submittedValue[0])
                        .getClass();
            }
        }
    }

    if (valueType == null) {
        // ...but have no idea of expected type
        // --> so let's convert it to an Object array
        int len = submittedValue.length;
        Object[] convertedValues = (Object[]) Array
                .newInstance(arrayComponentType == null ? Object.class : arrayComponentType, len);
        for (int i = 0; i < len; i++) {
            convertedValues[i] = converter.getAsObject(facesContext, component, submittedValue[i]);
        }
        return convertedValues;
    }

    if (List.class.isAssignableFrom(valueType)) {
        // Curious case: According to specs we should assume, that the element type
        // of this List is java.lang.String. But there is a Converter set for this
        // component. Because the user must know what he is doing, we will convert the values.
        int len = submittedValue.length;
        List lst = new ArrayList(len);
        for (int i = 0; i < len; i++) {
            lst.add(converter.getAsObject(facesContext, component, submittedValue[i]));
        }
        return lst;
    }

    if (arrayComponentType == null) {
        throw new IllegalArgumentException("ValueBinding for UISelectMany must be of type List or Array");
    }

    if (arrayComponentType.isPrimitive()) {
        //primitive array
        int len = submittedValue.length;
        Object convertedValues = Array.newInstance(arrayComponentType, len);
        for (int i = 0; i < len; i++) {
            Array.set(convertedValues, i, converter.getAsObject(facesContext, component, submittedValue[i]));
        }
        return convertedValues;
    } else {
        //Object array
        int len = submittedValue.length;
        ArrayList convertedValues = new ArrayList(len);
        for (int i = 0; i < len; i++) {
            convertedValues.add(i, converter.getAsObject(facesContext, component, submittedValue[i]));
        }
        return convertedValues.toArray((Object[]) Array.newInstance(arrayComponentType, len));
    }
}

From source file:net.sf.json.JSONDynaBean.java

/**
 * DOCUMENT ME!/*from w ww .ja  v  a  2  s .com*/
 *
 * @param name DOCUMENT ME!
 * @param index DOCUMENT ME!
 * @param value DOCUMENT ME!
 */
public void set(String name, int index, Object value) {
    Object prop = dynaValues.get(name);

    if (prop == null) {
        throw new NullPointerException("Unindexed property name: " + name + " index: " + index);
    } else if (!(prop instanceof List) || !(prop.getClass().isArray())) {
        throw new IllegalArgumentException("Non-Indexed property name: " + name + " index: " + index);
    }

    if (prop.getClass().isArray()) {
        Array.set(prop, index, value);
    } else if (value instanceof List) {
        ((List) prop).set(index, value);
    }
}

From source file:ro.pippo.csv.CsvEngine.java

@Override
@SuppressWarnings("unchecked")
public <T> T fromString(String content, Class<T> classOfT) {
    if (!classOfT.isArray()) {
        if (Collection.class.isAssignableFrom(classOfT)) {
            // Collections are NOT supported for deserialization from CSV
            throw new RuntimeException("Collection types are not supported. Please specify an array[] type.");
        }// w  w w. ja  v  a  2 s.co m
        throw new RuntimeException(
                String.format("Array[] types are required. Please specify %s[]", classOfT.getName()));
    }

    Class<?> objectType = classOfT.getComponentType();
    int currentLine = 0;
    try (CSVParser parser = new CSVParser(new StringReader(content), getCSVFormat().withHeader())) {
        Set<String> columns = parser.getHeaderMap().keySet();
        Map<String, Field> fieldMap = getFieldMap(objectType);

        Constructor<?> objectConstructor;
        try {
            objectConstructor = objectType.getConstructor();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("A default constructor is required for " + objectType.getName());
        }

        List objects = new ArrayList<>();
        for (CSVRecord record : parser) {
            currentLine++;

            Object o = objectConstructor.newInstance();
            for (String column : columns) {
                Field field = fieldMap.get(caseSensitiveFieldNames ? column : column.toLowerCase());
                String value = record.get(column);
                Object object = objectFromString(value, field.getType());
                field.set(o, object);
            }

            objects.add(o);
        }

        Object array = Array.newInstance(objectType, objects.size());
        for (int i = 0; i < objects.size(); i++) {
            Array.set(array, i, objects.get(i));
        }

        return (T) array;
    } catch (Exception e) {
        throw new RuntimeException("Failed to parse CSV near line #" + currentLine, e);
    }
}

From source file:org.primeframework.mvc.parameter.convert.AbstractAnnotationConverter.java

/**
 * This performs the conversion from a single String value to an array of the given type.
 *
 * @param annotation        The annotation from the field.
 * @param value             The value to convert to an array.
 * @param convertTo         The array type to convert to.
 * @param dynamicAttributes The dynamic attributes used to assist in conversion.
 * @param expression        The full path to the expression that is causing the conversion.
 * @return The converted value./*from   w ww .ja  v  a  2 s.  c om*/
 * @throws ConversionException     If the conversion failed.
 * @throws ConverterStateException if the converter didn't have all of the information it needed to perform the
 *                                 conversion.
 */
protected Object stringToArray(T annotation, String value, Type convertTo,
        Map<String, String> dynamicAttributes, String expression) throws ConversionException {
    if (value == null) {
        return null;
    }

    Object finalArray;
    Class<?> rawType = TypeTools.rawType(convertTo);
    if (StringUtils.isBlank(value)) {
        finalArray = Array.newInstance(rawType.getComponentType(), 0);
    } else {
        String[] parts = value.split(",");
        finalArray = Array.newInstance(rawType.getComponentType(), parts.length);
        for (int i = 0; i < parts.length; i++) {
            Object singleValue = stringToObject(annotation, parts[i], rawType.getComponentType(),
                    dynamicAttributes, expression);
            Array.set(finalArray, i, singleValue);
        }
    }

    return finalArray;
}

From source file:org.apache.hawq.pxf.plugins.hdfs.WritableResolver.java

/**
 * Sets customWritable fields and creates a OneRow object.
 *///from  www.  ja v  a 2  s .c o m
@Override
public OneRow setFields(List<OneField> record) throws Exception {
    Writable key = null;

    int colIdx = 0;
    for (Field field : fields) {
        /*
         * extract recordkey based on the column descriptor type
         * and add to OneRow.key
         */
        if (colIdx == recordkeyIndex) {
            key = recordkeyAdapter.convertKeyValue(record.get(colIdx).val);
            colIdx++;
        }

        if (Modifier.isPrivate(field.getModifiers())) {
            continue;
        }

        String javaType = field.getType().getName();
        convertJavaToGPDBType(javaType);
        if (isArray(javaType)) {
            Object value = field.get(userObject);
            int length = Array.getLength(value);
            for (int j = 0; j < length; j++, colIdx++) {
                Array.set(value, j, record.get(colIdx).val);
            }
        } else {
            field.set(userObject, record.get(colIdx).val);
            colIdx++;
        }
    }

    return new OneRow(key, userObject);
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.general.ArrayConverter.java

protected Object convertToArray(final Object value, final ValueConverter globalDelegate,
        final Class<?> expectedClass, final boolean toScript) {
    final Object result;
    final Class<?> valueClass = value.getClass();
    if (valueClass.isArray()) {
        final Object arr = Array.newInstance(expectedClass.getComponentType(), Array.getLength(value));

        for (int idx = 0; idx < Array.getLength(value); idx++) {
            final Object converted = toScript
                    ? globalDelegate.convertValueForScript(Array.get(value, idx),
                            expectedClass.getComponentType())
                    : globalDelegate.convertValueForJava(Array.get(value, idx),
                            expectedClass.getComponentType());
            Array.set(arr, idx, converted);
        }/*from  www  .ja  va2s  .  co m*/
        result = arr;
    } else {
        final Collection<?> coll;
        if (value instanceof Collection<?>) {
            coll = (Collection<?>) value;
        } else {
            final List<Object> list = new ArrayList<Object>();
            final Iterator<?> it = (Iterator<?>) value;
            while (it.hasNext()) {
                list.add(it.next());
            }
            coll = list;
        }

        final Object arr = Array.newInstance(expectedClass.getComponentType(), coll.size());
        final Iterator<?> it = coll.iterator();
        for (int idx = 0; it.hasNext(); idx++) {
            final Object converted = toScript
                    ? globalDelegate.convertValueForScript(it.next(), expectedClass.getComponentType())
                    : globalDelegate.convertValueForJava(it.next(), expectedClass.getComponentType());
            Array.set(arr, idx, converted);
        }
        result = arr;
    }
    return result;
}

From source file:org.droidparts.inner.converter.ArrayCollectionConverter.java

private final <T> Object parseTypeArr(Converter<T> converter, Class<T> valType, String[] arr) throws Exception {
    Object objArr = Array.newInstance(valType, arr.length);
    for (int i = 0; i < arr.length; i++) {
        T item = converter.parseFromString(valType, null, null, arr[i]);
        Array.set(objArr, i, item);
    }//from w ww. j  a v  a 2  s.c  om
    return objArr;
}

From source file:com.medallia.spider.api.DynamicInputImpl.java

/**
 * @param rt some kind of array class//from   w w  w  .  j a  v  a 2s. c o m
 * @param data null, String or String[]
 * @return parsed data as per parseSingleValue
 * @throws AssertionError if parseSingleValue does
 */
private Object parseMultiValue(Class<?> rt, Object data, AnnotatedElement anno) throws AssertionError {
    String[] xs;
    // normalize the zero-and-one cases
    if (data == null) {
        xs = new String[0];
    } else if (data instanceof String[]) {
        xs = (String[]) data;
    } else {
        xs = new String[] { data.toString() };
    }

    Class<?> comp = rt.getComponentType();
    Object arr = Array.newInstance(rt.getComponentType(), xs.length);
    for (int i = 0; i < xs.length; i++) {
        Array.set(arr, i, parseSingleValue(comp, xs[i], anno, inputArgParsers));
    }
    return arr;
}