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:ArrayMap.java

private static void put(Object array, Object element, int index) {
    try {//  w w w. j av  a2s.  c  o  m
        if (array instanceof Object[]) {
            try {
                ((Object[]) array)[index] = element;
            } catch (ArrayStoreException e) {
                throw new IllegalArgumentException(
                        e.getMessage() + ": " + (element == null ? "null" : element.getClass().getName())
                                + " into " + array.getClass().getName());
            }
        } else {
            try {
                Array.set(array, index, element);
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException(
                        e.getMessage() + ": " + (element == null ? "null" : element.getClass().getName())
                                + " into " + array.getClass().getName(),
                        e);
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new ArrayIndexOutOfBoundsException(index + " into " + Array.getLength(array));
    }
}

From source file:org.bitpipeline.lib.friendlyjson.JSONEntity.java

/** Des-serialize a JSON object.
 * @throws JSONException/*from  w  ww  . j a va  2s.  c  om*/
 * @throws JSONMappingException */
public JSONEntity(JSONObject json) throws JSONMappingException {
    if (json == null)
        return;
    Class<?> clazz = this.getClass();
    List<Field> declaredFields = new ArrayList<Field>();
    do {
        Field[] fields = clazz.getDeclaredFields();
        declaredFields.addAll(Arrays.asList(fields));
        clazz = clazz.getSuperclass();
    } while (clazz != null && !clazz.isAssignableFrom(JSONEntity.class));
    for (Field field : declaredFields) {
        if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { // don't care about transient fields.
            continue;
        }

        String fieldName = field.getName();
        if (fieldName.equals("this$0"))
            continue;

        boolean accessible = field.isAccessible();
        if (!accessible)
            field.setAccessible(true);

        Class<?> type = field.getType();

        if (type.isArray()) {
            Class<?> componentClass = type.getComponentType();
            JSONArray jsonArray = null;
            try {
                jsonArray = json.getJSONArray(fieldName);
            } catch (JSONException e) {
                // no data for this field found.
                continue;
            }

            int size = jsonArray.length();

            Object array = Array.newInstance(componentClass, size);
            for (int i = 0; i < size; i++) {
                try {
                    Object item = fromJson(componentClass, jsonArray.get(i));
                    Array.set(array, i, item);
                } catch (Exception e) {
                    System.err.println("Invalid array component for class " + this.getClass().getName()
                            + " field " + field.getName() + "::" + field.getType().getName());
                }
            }

            try {
                field.set(this, array);
            } catch (Exception e) {
                throw new JSONMappingException(e);
            }
        } else if (JSONEntity.class.isAssignableFrom(type)) {
            try {
                Object entity = readJSONEntity(type, json.getJSONObject(fieldName));
                field.set(this, entity);
            } catch (JSONException e) {
                // keep going.. the json representation doesn't have value for this field.
            } catch (Exception e) {
                throw new JSONMappingException(e);
            }
        } else {
            FieldSetter setter = JSON_READERS.get(type.getName());
            if (setter != null) {
                try {
                    setter.setField(this, field, json, fieldName);
                } catch (JSONException e) {
                    // do nothing. We just didn't receive data for this field
                } catch (Exception e) {
                    throw new JSONMappingException(e);
                }
            } else {
                Object jsonObj;
                try {
                    jsonObj = json.get(fieldName);
                } catch (Exception e) {
                    jsonObj = null;
                }
                if (jsonObj != null) {
                    Object value = fromJson(type, jsonObj);
                    try {
                        field.set(this, value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    System.err.println("No setter for " + field);
                }

            }
        }

        if (!accessible)
            field.setAccessible(false);
    }
}

From source file:nl.strohalm.cyclos.utils.binding.MapBean.java

@SuppressWarnings("unchecked")
public void set(final String name, final int index, final Object value) {
    final Object bean = this.get(name);
    if (bean != null) {
        if (bean instanceof List) {
            ((List<Object>) bean).set(index, value);
        } else if (value.getClass().isArray()) {
            Array.set(bean, index, value);
        }//  ww  w .j  a  v  a  2  s  .  c o  m
    }
}

From source file:org.mstc.zmq.json.Decoder.java

@SuppressWarnings("unchecked")
public static void decode(String input, Field[] fields, Object b) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    if (logger.isDebugEnabled())
        logger.debug(input);/*from www. ja v a  2  s .c o m*/
    JsonFactory factory = mapper.getFactory();
    try (JsonParser jp = factory.createParser(input)) {
        /* Sanity check: verify that we got "Json Object" */
        if (jp.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }

        /* Iterate over object fields */
        while (jp.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = jp.getCurrentName();
            jp.nextToken();
            Field field = getField(fieldName, fields);
            if (field == null) {
                throw new IOException(
                        "Could not find field [" + fieldName + "] on class " + b.getClass().getName());
            }
            try {
                if (field.getType().isAssignableFrom(List.class)) {
                    String adder = getAdder(fieldName);
                    TypeFactory t = TypeFactory.defaultInstance();
                    ParameterizedType listType = (ParameterizedType) field.getGenericType();
                    Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0];
                    List list = mapper.readValue(jp.getValueAsString(),
                            t.constructCollectionType(List.class, listClass));
                    Method m = b.getClass().getDeclaredMethod(adder, Collection.class);
                    m.invoke(b, list);
                } else if (field.getType().isArray()) {
                    Class<?> type = field.getType();
                    String setter = getSetter(fieldName);
                    Method m = b.getClass().getDeclaredMethod(setter, field.getType());
                    logger.info("Field {} is array of {}[], {}, using method {}", field.getName(),
                            field.getType().getComponentType(), jp.getCurrentToken().name(), m);
                    if (jp.getCurrentToken().id() == JsonToken.START_ARRAY.id()) {
                        List list = new ArrayList();
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            String value = jp.getText();
                            switch (jp.getCurrentToken()) {
                            case VALUE_STRING:
                                list.add(value);
                                break;
                            case VALUE_NUMBER_INT:
                                if (type.getComponentType().isAssignableFrom(double.class)) {
                                    list.add(Double.parseDouble(value));
                                } else if (type.getComponentType().isAssignableFrom(float.class)) {
                                    list.add(Float.parseFloat(value));
                                } else {
                                    list.add(Integer.parseInt(value));
                                }
                                break;
                            case VALUE_NUMBER_FLOAT:
                                logger.info("Add float");
                                list.add(jp.getFloatValue());
                                break;
                            case VALUE_NULL:
                                break;
                            default:
                                logger.warn("[3] Not sure how to handle {} yet", jp.getCurrentToken().name());
                            }
                        }
                        Object array = Array.newInstance(field.getType().getComponentType(), list.size());
                        for (int i = 0; i < list.size(); i++) {
                            Object val = list.get(i);
                            Array.set(array, i, val);
                        }
                        m.invoke(b, array);
                    } else {
                        if (type.getComponentType().isAssignableFrom(byte.class)) {
                            m.invoke(b, jp.getBinaryValue());
                        }
                    }
                } else {
                    String setter = getSetter(fieldName);
                    logger.debug("{}: {}", setter, field.getType().getName());
                    Method m = b.getClass().getDeclaredMethod(setter, field.getType());

                    switch (jp.getCurrentToken()) {
                    case VALUE_STRING:
                        m.invoke(b, jp.getText());
                        break;
                    case VALUE_NUMBER_INT:
                        m.invoke(b, jp.getIntValue());
                        break;
                    case VALUE_NUMBER_FLOAT:
                        m.invoke(b, jp.getFloatValue());
                        break;
                    case VALUE_NULL:
                        logger.debug("Skip invoking {}.{}, property is null", b.getClass().getName(),
                                m.getName());
                        break;
                    case START_OBJECT:
                        StringBuilder sb = new StringBuilder();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            switch (jp.getCurrentToken()) {
                            case VALUE_STRING:
                                sb.append("\"").append(jp.getText()).append("\"");
                                break;
                            case FIELD_NAME:
                                if (sb.length() > 0)
                                    sb.append(",");
                                sb.append("\"").append(jp.getText()).append("\"").append(":");
                                break;
                            case VALUE_NUMBER_INT:
                                sb.append(jp.getIntValue());
                                break;
                            case VALUE_NUMBER_FLOAT:
                                sb.append(jp.getFloatValue());
                                break;
                            case VALUE_NULL:
                                sb.append("null");
                                break;
                            default:
                                logger.warn("[2] Not sure how to handle {} yet", jp.getCurrentToken().name());
                            }
                        }
                        String s = String.format("%s%s%s", JsonToken.START_OBJECT.asString(), sb.toString(),
                                JsonToken.END_OBJECT.asString());
                        Object parsed = getNested(field.getType(), s.getBytes());
                        m.invoke(b, parsed);
                        break;
                    default:
                        logger.warn("[1] Not sure how to handle {} yet", jp.getCurrentToken().name());
                    }
                }
            } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException
                    | IllegalArgumentException e) {
                logger.error("Failed setting field [{}], builder: {}", fieldName, b.getClass().getName(), e);
            }
        }
    }
}

From source file:com.microsoft.tfs.core.internal.wrappers.WrapperUtils.java

/**
 * <p>/*  w w w.  j a v a2s  .co  m*/
 * Takes an array of web service wrapper (for example, an array of
 * {@link Item}) and returns an array of the wrapped web service objects
 * that were inside the given type (for instance, {@link _Item}).
 * </p>
 * <p>
 * A public method named {@link #UNWRAP_METHOD_NAME} which takes no
 * arguments and returns the wrapped web service object must exist.
 * </p>
 * <p>
 * <code>null</code> values in the wrapper objects will be persisted in the
 * returned array.
 * </p>
 *
 * @param webServiceObjectType
 *        the type of the wrapped web service object (not array type) (not
 *        null)
 * @param wrapperObjects
 *        the wrapper objects to get the contents from(if null, null is
 *        returned)
 * @return a new array of web service objects, each extracted from the given
 *         wrapper objects
 */
public static Object unwrap(final Class webServiceObjectType, final Object[] wrapperObjects) {
    Check.notNull(webServiceObjectType, "webServiceObjectType"); //$NON-NLS-1$

    if (wrapperObjects == null) {
        return null;
    }

    final Object ret = Array.newInstance(webServiceObjectType, wrapperObjects.length);
    if (wrapperObjects.length > 0) {
        try {
            Method method = null;
            for (int i = 0; i < wrapperObjects.length; i++) {
                if (method == null && wrapperObjects[i] != null) {
                    method = wrapperObjects[i].getClass().getMethod(UNWRAP_METHOD_NAME, new Class[0]);
                }

                /*
                 * Persist null values.
                 */
                Array.set(ret, i,
                        (wrapperObjects[i] != null) ? method.invoke(wrapperObjects[i], new Object[0]) : null);
            }

        } catch (final NoSuchMethodException e) {
            final String message = MessageFormat.format(
                    "Wrapper error: the given wrapper class {0} does not have a method named {1} that returns a {2}", //$NON-NLS-1$
                    wrapperObjects[0].getClass(), UNWRAP_METHOD_NAME, webServiceObjectType);

            log.error(message, e);
            throw new RuntimeException(message, e);
        } catch (final Exception e) {
            final String message = MessageFormat.format("Error unwrapping {0} from {1}", //$NON-NLS-1$
                    webServiceObjectType, wrapperObjects);

            log.error(message, e);
            throw new RuntimeException(message, e);
        }
    }
    return ret;
}

From source file:com.jaspersoft.jasperserver.remote.utils.RepositoryHelper.java

protected static Object getMultiParameterValues(JRParameter parameter, Collection values) {
    Object parameterValue;/*from   ww  w .ja v  a  2s. c  om*/
    Class parameterType = parameter.getValueClass();
    if (parameterType.equals(Object.class) || parameterType.equals(Collection.class)
            || parameterType.equals(Set.class) || parameterType.equals(List.class)) {
        Collection paramValues;
        if (parameterType.equals(List.class)) {
            //if the parameter type is list, use a list
            paramValues = new ArrayList(values.size());
        } else {
            //else use an ordered set
            paramValues = new ListOrderedSet();
        }

        Class componentType = parameter.getNestedType();
        for (Iterator it = values.iterator(); it.hasNext();) {
            Object val = (Object) it.next();
            Object paramValue;
            if (componentType == null || !(val instanceof String)) {
                //no conversion if no nested type set for the parameter
                paramValue = val;
            } else {
                paramValue = stringToValue((String) val, componentType);
            }
            paramValues.add(paramValue);
        }
        parameterValue = paramValues;
    } else if (parameterType.isArray()) {
        Class componentType = parameterType.getComponentType();
        parameterValue = Array.newInstance(componentType, values.size());
        int idx = 0;
        for (Iterator iter = values.iterator(); iter.hasNext(); ++idx) {
            Object val = iter.next();
            Object paramValue;
            if (val instanceof String) {
                paramValue = stringToValue((String) val, componentType);
            } else {
                paramValue = val;
            }
            Array.set(parameterValue, idx, paramValue);
        }
    } else {
        parameterValue = values;
    }
    return parameterValue;
}

From source file:com.nfwork.dbfound.json.JSONDynaBean.java

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);
    }/*from  ww w .  j  av  a 2  s .c o  m*/
    if (prop.getClass().isArray()) {
        Array.set(prop, index, value);
    } else if (value instanceof List) {
        ((List) prop).set(index, value);
    }
}

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

@SuppressWarnings("unchecked")
public Object toObject() throws PersistenceException {
    if (collectionType == null) {
        ConnectorPropertyJPAEntity entity = properties.toArray(new ConnectorPropertyJPAEntity[1])[0];
        return entity.toObject();
    }/*from  ww  w  .ja va2 s.  c o  m*/
    try {
        Class<?> collectionClass = Class.forName(collectionType);
        if (collectionClass.isArray()) {
            Object arr = Array.newInstance(collectionClass.getComponentType(), properties.size());
            int i = 0;
            for (ConnectorPropertyJPAEntity entity : properties) {
                Array.set(arr, i, entity.toObject());
                i++;
            }
            return arr;
        } else {
            Collection<Object> collection = (Collection<Object>) collectionClass.newInstance();
            for (ConnectorPropertyJPAEntity entity : properties) {
                collection.add(entity.toObject());
            }
            return collection;
        }
    } catch (ClassNotFoundException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    }
}

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

@SuppressWarnings("unchecked")
protected <V> Object readFromWrapper(Class<Object> valType, Class<V> genericArg1, Wrapper wrapper)
        throws Exception {
    boolean isArr = isArray(valType);
    boolean isModel = isModel(genericArg1);
    Collection<Object> items;
    if (isArr) {//w ww. j  av a 2  s.co  m
        items = new ArrayList<Object>();
    } else {
        items = (Collection<Object>) newInstance(valType);
    }
    Converter<V> converter = ConverterRegistry.getConverter(genericArg1);
    for (int i = 0; i < wrapper.size(); i++) {
        Object item = wrapper.get(i);
        if (isModel) {
            item = wrapper.deserialize(item, converter, genericArg1);
        } else {
            item = wrapper.convert(item, converter, genericArg1);
        }
        items.add(item);
    }
    if (isArr) {
        Object[] arr = items.toArray();
        if (isModel) {
            Object modelArr = Array.newInstance(genericArg1, arr.length);
            for (int i = 0; i < arr.length; i++) {
                Array.set(modelArr, i, arr[i]);
            }
            return modelArr;
        } else {
            String[] arr2 = new String[arr.length];
            for (int i = 0; i < arr.length; i++) {
                arr2[i] = arr[i].toString();
            }
            return parseTypeArr(converter, genericArg1, arr2);
        }
    } else {
        return items;
    }
}

From source file:com.sinosoft.one.data.jade.statement.SelectQuerier.java

public Object execute(SQLType sqlType, StatementRuntime runtime) {
    String sql = runtime.getSQL();
    Object[] args = runtime.getArgs();
    DataAccess dataAccess = new DataAccessImpl(em);
    List<?> listResult = null;
    Pageable pageable = null;//from   w  ww.  j  av a  2s . co  m
    Sort sort = null;
    boolean isPage = false;
    boolean isSort = false;
    Map<String, Object> paramMap = runtime.getParameters();
    for (String key : paramMap.keySet()) {
        if (paramMap.get(key) instanceof Pageable) {
            pageable = (Pageable) paramMap.get(key);
            isPage = true;
        } else if (paramMap.get(key) instanceof Sort) {
            sort = (Sort) paramMap.get(key);
            isSort = true;
        }
    }
    if (isPage && !isSort) {
        if (returnType == Page.class) {
            String countSql = parseCountSql(sql);
            Page<?> page = dataAccess.selectByPage(pageable, sql, countSql, args, rowMapper);
            return page;
        } else {
            try {
                log.error("The return type[" + returnType + "] must be " + Page.class);
                throw new Exception("The return type [\"+returnType+\"] is invalid");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } else if (!isPage && isSort) {
        return dataAccess.selectBySort(sort, sql, args, rowMapper);
    } else if (isPage && isSort) {
        try {
            log.error("Can not use Params:[" + Pageable.class + " and " + Sort.class + "at the same time.");
            throw new Exception(
                    "Can not use Params:[" + Pageable.class + " and " + Sort.class + "at the same time.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {

        listResult = dataAccess.select(sql, args, 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 + ": "
                            + runtime.getMetaData();
                    throw new EmptyResultDataAccessException(msg, 1);
                } else {
                    return null;
                }

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