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:net.sourceforge.jaulp.lang.ObjectUtils.java

/**
 * Try to clone the given object.// w w  w  . j  ava  2  s . c  o m
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             the no such method exception
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws ClassNotFoundException
 *             the class not found exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectUtils.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        Class<?> clazz = object.getClass();
        Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionUtils.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:com.adobe.acs.commons.util.impl.ValueMapTypeConverter.java

private Object unwrapArray(Object wrapperArray, Class<?> primitiveType) {
    int length = Array.getLength(wrapperArray);
    Object primitiveArray = Array.newInstance(primitiveType, length);
    for (int i = 0; i < length; i++) {
        Array.set(primitiveArray, i, Array.get(wrapperArray, i));
    }/*  www  .  ja v a2  s  .c  o  m*/
    return primitiveArray;
}

From source file:de.hasait.clap.impl.CLAPOptionNode.java

private CLAPOptionNode(final CLAP pCLAP, final Class<T> pResultClass, final Character pShortKey,
        final String pLongKey, final boolean pRequired, final Integer pArgCount, final Character pMultiArgSplit,
        final String pDescriptionNLSKey, final String pArgUsageNLSKey) {
    super(pCLAP);

    if (pShortKey != null && pShortKey == getCLAP().getShortOptPrefix()) {
        throw new IllegalArgumentException();
    }//  w  w w  .  j  a v a 2s  .  co m
    if (pLongKey != null && pLongKey.contains(getCLAP().getLongOptEquals())) {
        throw new IllegalArgumentException();
    }

    if (pArgCount == null) {
        // autodetect using resultClass
        if (pResultClass.isArray() || Collection.class.isAssignableFrom(pResultClass)) {
            _argCount = CLAP.UNLIMITED_ARG_COUNT;
        } else if (pResultClass.equals(Boolean.class) || pResultClass.equals(Boolean.TYPE)) {
            _argCount = 0;
        } else {
            _argCount = 1;
        }
    } else {
        if (pArgCount < 0 && pArgCount != CLAP.UNLIMITED_ARG_COUNT) {
            throw new IllegalArgumentException();
        }

        if (pResultClass.isArray() || Collection.class.isAssignableFrom(pResultClass)) {
            if (pArgCount == 0) {
                throw new IllegalArgumentException();
            }
        } else if (pResultClass.equals(Boolean.class) || pResultClass.equals(Boolean.TYPE)) {
            if (pArgCount != 0 && pArgCount != 1) {
                throw new IllegalArgumentException();
            }
        } else {
            if (pArgCount != 1) {
                throw new IllegalArgumentException();
            }
        }

        _argCount = pArgCount;
    }

    if (pShortKey == null && pLongKey == null && _argCount == 0) {
        throw new IllegalArgumentException();
    }

    if (pResultClass.isArray()) {
        final Class<?> componentType = pResultClass.getComponentType();
        final CLAPConverter<?> converter = pCLAP.getConverter(componentType);
        _mapper = new Mapper<T>() {

            @Override
            public T transform(final String[] pStringValues) {
                final T result = (T) Array.newInstance(componentType, pStringValues.length);
                for (int i = 0; i < pStringValues.length; i++) {
                    try {
                        Array.set(result, i, converter.convert(pStringValues[i]));
                    } catch (final Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                return result;
            }

        };
    } else if (Collection.class.isAssignableFrom(pResultClass)) {
        _mapper = null;
    } else {
        final CLAPConverter<? extends T> converter = pCLAP.getConverter(pResultClass);
        _mapper = new Mapper<T>() {

            @Override
            public T transform(final String[] pStringValues) {
                if (pStringValues.length == 0
                        && (pResultClass.equals(Boolean.class) || pResultClass.equals(Boolean.TYPE))) {
                    return (T) Boolean.TRUE;
                }
                return converter.convert(pStringValues[0]);
            }

        };
    }

    _shortKey = pShortKey;
    _longKey = pLongKey;
    _required = pRequired;
    _multiArgSplit = pMultiArgSplit;
    _descriptionNLSKey = pDescriptionNLSKey;
    _argUsageNLSKey = pArgUsageNLSKey;
    _resultClass = pResultClass;
}

From source file:com.alibaba.dubbo.governance.web.common.module.screen.Restful.java

public void execute(Map<String, Object> context) throws Throwable {
    if (context.get(WebConstants.CURRENT_USER_KEY) != null) {
        User user = (User) context.get(WebConstants.CURRENT_USER_KEY);
        currentUser = user;//from  w  w w.  j av  a 2 s .  co m
        operator = user.getUsername();
        role = user.getRole();
        context.put(WebConstants.CURRENT_USER_KEY, user);
    }
    operatorAddress = (String) context.get("request.remoteHost");
    context.put("operator", operator);
    context.put("operatorAddress", operatorAddress);

    context.put("currentRegistry", currentRegistry);

    String httpMethod = (String) context.get("request.method");
    String method = (String) context.get("_method");
    String contextPath = (String) context.get("request.contextPath");
    context.put("rootContextPath", new RootContextPath(contextPath));

    // ?Method
    if (method == null || method.length() == 0) {
        String id = (String) context.get("id");
        if (id == null || id.length() == 0) {
            method = "index";
        } else {
            method = "show";
        }
    }
    if ("index".equals(method)) {
        if ("post".equalsIgnoreCase(httpMethod)) {
            method = "create";
        }
    } else if ("show".equals(method)) {
        if ("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // ????PUTPOST
            method = "update";
        } else if ("delete".equalsIgnoreCase(httpMethod)) { // ????DELETE?
            method = "delete";
        }
    }
    context.put("_method", method);

    try {
        Method m = null;
        try {
            m = getClass().getMethod(method, new Class<?>[] { Map.class });
        } catch (NoSuchMethodException e) {
            for (Method mtd : getClass().getMethods()) {
                if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().equals(method)) {
                    m = mtd;
                    break;
                }
            }
            if (m == null) {
                throw e;
            }
        }
        if (m.getParameterTypes().length > 2) {
            throw new IllegalStateException("Unsupport restful method " + m);
        } else if (m.getParameterTypes().length == 2 && (m.getParameterTypes()[0].equals(Map.class)
                || !m.getParameterTypes()[1].equals(Map.class))) {
            throw new IllegalStateException("Unsupport restful method " + m);
        }
        Object r;
        if (m.getParameterTypes().length == 0) {
            r = m.invoke(this, new Object[0]);
        } else {
            Object value;
            Class<?> t = m.getParameterTypes()[0];
            if (Map.class.equals(t)) {
                value = context;
            } else if (isPrimitive(t)) {
                String id = (String) context.get("id");
                value = convertPrimitive(t, id);
            } else if (t.isArray() && isPrimitive(t.getComponentType())) {
                String id = (String) context.get("id");
                String[] ids = id == null ? new String[0] : id.split("[.+]+");
                value = Array.newInstance(t.getComponentType(), ids.length);
                for (int i = 0; i < ids.length; i++) {
                    Array.set(value, i, convertPrimitive(t.getComponentType(), ids[i]));
                }
            } else {
                value = t.newInstance();
                for (Method mtd : t.getMethods()) {
                    if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().startsWith("set")
                            && mtd.getParameterTypes().length == 1) {
                        String p = mtd.getName().substring(3, 4).toLowerCase() + mtd.getName().substring(4);
                        Object v = context.get(p);
                        if (v == null) {
                            if ("operator".equals(p)) {
                                v = operator;
                            } else if ("operatorAddress".equals(p)) {
                                v = (String) context.get("request.remoteHost");
                            }
                        }
                        if (v != null) {
                            try {
                                mtd.invoke(value, new Object[] { CompatibleTypeUtils.compatibleTypeConvert(v,
                                        mtd.getParameterTypes()[0]) });
                            } catch (Throwable e) {
                                logger.warn(e.getMessage(), e);
                            }
                        }
                    }
                }
            }
            if (m.getParameterTypes().length == 1) {
                r = m.invoke(this, new Object[] { value });
            } else {
                r = m.invoke(this, new Object[] { value, context });
            }
        }
        if (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class) {
            context.put("rundata.layout", "redirect");
            context.put("rundata.target", "redirect");
            context.put("success", r == null || ((Boolean) r).booleanValue());
            if (context.get("redirect") == null) {
                context.put("redirect", getDefaultRedirect(context, method));
            }
        } else if (m.getReturnType() == String.class) {
            String redirect = (String) r;
            if (redirect == null) {
                redirect = getDefaultRedirect(context, method);
            }

            if (context.get("chain") != null) {
                context.put("rundata.layout", "home");
                context.put("rundata.target", "home");
            } else {
                context.put("rundata.redirect", redirect);
            }
        } else {
            context.put("rundata.layout", method);
            context.put("rundata.target", context.get("rundata.target") + "/" + method);
        }
    } catch (Throwable e) {
        if (e instanceof InvocationTargetException) {
            throw ((InvocationTargetException) e).getTargetException();
        }
        //            if (e instanceof InvocationTargetException) {
        //                e = ((InvocationTargetException) e).getTargetException();
        //            }
        //            logger.warn(e.getMessage(), e);
        //            context.put("rundata.layout", "redirect");
        //            context.put("rundata.target", "redirect");
        //            context.put("success", false);
        //            context.put("exception", e);
        //            context.put("redirect", getDefaultRedirect(context, method));
    }
}

From source file:org.kv.KVConfig.java

/**
 * Code to read a json file into this structure.
 * Sorta possible with the json library, but this works
 *
 * @param configFile File to read./*from w ww  .  j  a v a 2  s. c o m*/
 * @return A KVConfig instance with values set from the file.
 */
public static KVConfig load(File configFile) {
    try {
        BufferedReader in = new BufferedReader(new FileReader(configFile));
        KVConfig config = new KVConfig();

        // read the whole file into a single string
        String jsonStr = "";
        String line;
        while ((line = in.readLine()) != null)
            jsonStr += line + "\n";
        in.close();

        // build a json object from the string
        JSONObject json = new JSONObject(jsonStr);

        // while there are keys, set the members of the KVConfig instance
        Iterator<?> keyiter = json.keys();
        while (keyiter.hasNext()) {
            String key = (String) keyiter.next();
            Field field = KVConfig.class.getField(key);

            // handle arrays first, then scalars
            if (field.getType().isArray()) {
                JSONArray array = json.getJSONArray(key);
                Class<?> component = field.getType().getComponentType();

                Object value = Array.newInstance(component, array.length());
                for (int i = 0; i < array.length(); i++) {
                    if (component == int.class) {
                        Array.setInt(value, i, array.getInt(i));
                    }
                    if (component == long.class) {
                        Array.setLong(value, i, array.getLong(i));
                    } else if (component == String.class) {
                        Array.set(value, i, array.getString(i));
                    } else if (component == double.class) {
                        Array.setDouble(value, i, array.getDouble(i));
                    }
                }

                field.set(config, value);
            } else if (field.getType() == int.class) {
                field.setInt(config, json.getInt(key));
            } else if (field.getType() == long.class) {
                field.setLong(config, json.getLong(key));
            } else if (field.getType() == String.class) {
                field.set(config, json.getString(key));
            } else if (field.getType() == double.class) {
                field.set(config, json.getDouble(key));
            }
        }

        return config;

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }

    return null;
}

From source file:com.jaspersoft.jasperserver.ws.axis2.RepositoryHelper.java

protected Object getMultiParameterValues(JRParameter parameter, Collection values) {
    Object parameterValue;//w  w w.  j a  v  a  2 s  .co  m
    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:org.pentaho.reporting.platform.plugin.ReportContentUtil.java

public static Object computeParameterValue(final ParameterContext parameterContext,
        final ParameterDefinitionEntry parameterDefinition, final Object value)
        throws ReportProcessingException {
    if (value == null) {
        // there are still buggy report definitions out there ...
        return null;
    }//w  w w .j  a  va2 s . c  o m

    final Class valueType = parameterDefinition.getValueType();
    final boolean allowMultiSelect = isAllowMultiSelect(parameterDefinition);
    if (allowMultiSelect && Collection.class.isInstance(value)) {
        final Collection c = (Collection) value;
        final Class componentType;
        if (valueType.isArray()) {
            componentType = valueType.getComponentType();
        } else {
            componentType = valueType;
        }

        final int length = c.size();
        final Object[] sourceArray = c.toArray();
        final Object array = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(array, i, convert(parameterContext, parameterDefinition, componentType, sourceArray[i]));
        }
        return array;
    } else if (value.getClass().isArray()) {
        final Class componentType;
        if (valueType.isArray()) {
            componentType = valueType.getComponentType();
        } else {
            componentType = valueType;
        }

        final int length = Array.getLength(value);
        final Object array = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(array, i,
                    convert(parameterContext, parameterDefinition, componentType, Array.get(value, i)));
        }
        return array;
    } else if (allowMultiSelect) {
        // if the parameter allows multi selections, wrap this single input in an array
        // and re-call addParameter with it
        final Object[] array = new Object[1];
        array[0] = value;
        return computeParameterValue(parameterContext, parameterDefinition, array);
    } else {
        return convert(parameterContext, parameterDefinition, parameterDefinition.getValueType(), value);
    }
}

From source file:org.opoo.util.ClassUtils.java

public static Object getProperties(final Object entity, final String[] names, final Class type) {
    Object array = Array.newInstance(type, names.length);
    for (int i = 0; i < names.length; i++) {
        Object value = getProperty(entity, names[i]);
        Array.set(array, i, value);
    }/*from www .  ja  v  a2s .  c  om*/
    return array;
}

From source file:com.gzj.tulip.jade.statement.SelectQuerier.java

protected ResultConverter makeResultConveter() {
    ResultConverter converter;/* www  . j  a v a2  s .c o  m*/
    if (List.class == returnType || Collection.class == returnType || Iterable.class == returnType) {
        converter = new ResultConverter() {

            @Override
            public Object convert(StatementRuntime runtime, List<?> listResult) {
                return listResult;
            }

        };
    } else if (ArrayList.class == returnType) {
        converter = new ResultConverter() {

            @Override
            public Object convert(StatementRuntime runtime, List<?> listResult) {
                return new ArrayList(listResult);
            }

        };
    } else if (LinkedList.class == returnType) {
        converter = new ResultConverter() {

            @Override
            public Object convert(StatementRuntime runtime, List<?> listResult) {
                return new LinkedList(listResult);
            }

        };
    } else if (Set.class == returnType || HashSet.class == returnType) {
        converter = new ResultConverter() {

            @Override
            public Object convert(StatementRuntime runtime, List<?> listResult) {
                return new HashSet(listResult);
            }

        };
    } else if (Collection.class.isAssignableFrom(returnType)) {
        converter = new ResultConverter() {

            @Override
            public Object convert(StatementRuntime runtime, List<?> listResult) {
                Collection listToReturn;
                try {
                    listToReturn = (Collection) returnType.newInstance();
                } catch (Exception e) {
                    throw new Error("error to create instance of " + returnType.getName());
                }
                listToReturn.addAll(listResult);
                return listToReturn;
            }

        };
    } else if (Iterator.class == returnType) {
        converter = new ResultConverter() {

            @Override
            public Object convert(StatementRuntime runtime, List<?> listResult) {
                return listResult.iterator();
            }

        };
    } else if (returnType.isArray() && byte[].class != returnType) {
        if (returnType.getComponentType().isPrimitive()) {
            converter = new ResultConverter() {

                @Override
                public Object convert(StatementRuntime runtime, List<?> listResult) {
                    Object array = Array.newInstance(returnType.getComponentType(), listResult.size());
                    int len = listResult.size();
                    for (int i = 0; i < len; i++) {
                        Array.set(array, i, listResult.get(i));
                    }
                    return array;
                }

            };
        } else {
            converter = new ResultConverter() {

                @Override
                public Object convert(StatementRuntime runtime, List<?> listResult) {
                    Object array = Array.newInstance(returnType.getComponentType(), listResult.size());
                    return listResult.toArray((Object[]) array);
                }

            };
        }

    } else if (Map.class == returnType || HashMap.class == returnType) {
        converter = new MapConverter() {
            @Override
            protected Map creatMap(StatementRuntime runtime) {
                return new HashMap();
            }
        };
    } else if (Hashtable.class == returnType) {
        converter = new MapConverter() {
            @Override
            protected Map creatMap(StatementRuntime runtime) {
                return new Hashtable();
            }
        };
    } else if (Map.class.isAssignableFrom(returnType)) {
        converter = new MapConverter() {
            @Override
            protected Map creatMap(StatementRuntime runtime) {
                try {
                    return (Map) returnType.newInstance();
                } catch (Exception e) {
                    throw new Error("error to create instance of " + returnType.getName());
                }
            }
        };
    }
    // 
    else {
        converter = new ResultConverter() {

            @Override
            public Object convert(StatementRuntime runtime, List<?> listResult) {
                final int sizeResult = listResult.size();
                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 converter;
}

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

private Object wrapArray(Object primitiveArray, Class<?> wrapperType) {
    int length = Array.getLength(primitiveArray);
    Object wrapperArray = Array.newInstance(wrapperType, length);
    for (int i = 0; i < length; i++) {
        Array.set(wrapperArray, i, Array.get(primitiveArray, i));
    }//from  ww  w. j  av  a 2s . c om
    return wrapperArray;
}