Example usage for java.lang.reflect Array newInstance

List of usage examples for java.lang.reflect Array newInstance

Introduction

In this page you can find the example usage for java.lang.reflect Array newInstance.

Prototype

public static Object newInstance(Class<?> componentType, int... dimensions)
        throws IllegalArgumentException, NegativeArraySizeException 

Source Link

Document

Creates a new array with the specified component type and dimensions.

Usage

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 ww .  j ava  2  s  .  c  o 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:Main.java

/**
 * Ensures the given array has a given size.
 * @param array        the array./*from ww w .  j av  a2 s  . c o m*/
 * @param size         the target size of the array.
 * @param initialValue the initial value of the elements.
 * @return             the original array, or a copy if it had to be
 *                     extended.
 */
public static Object[] ensureArraySize(Object[] array, int size, Object initialValue) {
    // Is the existing array large enough?
    if (array.length >= size) {
        // Reinitialize the existing array.
        Arrays.fill(array, 0, size, initialValue);
    } else {
        // Otherwise create and initialize a new array.
        array = (Object[]) Array.newInstance(array.getClass().getComponentType(), size);

        if (initialValue != null) {
            Arrays.fill(array, 0, size, initialValue);
        }
    }

    return array;
}

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

protected Object getMultiParameterValues(JRParameter parameter, Collection values) {
    Object parameterValue;/*from  ww  w  . j a va 2 s . 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.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));
    }//w w w.j a  v  a  2s.  c  o m
    return primitiveArray;
}

From source file:jease.cmf.domain.Node.java

/**
 * Returns all descendant nodes of given class type by recursively
 * traversing children./*  www. j av  a2 s. com*/
 */
public <E extends Node> E[] getDescendants(final Class<E> clazz) {
    return (E[]) Stream.of(getDescendants()).filter($node -> clazz.isAssignableFrom($node.getClass()))
            .toArray($size -> (E[]) Array.newInstance(clazz, $size));
}

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  ww  .jav 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:jfix.util.Reflections.java

/**
 * Returns all instanceable (sub-)classes of given type in given package.
 *//*from   w w w. j  av a  2 s .c o  m*/
public static <E> E[] find(Class<E> classType, Package pckage) {
    File directory;
    try {
        String name = "/" + pckage.getName().replace('.', '/');
        directory = new File(classType.getResource(name).toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    List<E> result = new ArrayList<>();
    if (directory.exists()) {
        String[] files = directory.list();
        for (int i = 0; i < files.length; i++) {
            if (files[i].endsWith(".class")) {
                String classname = files[i].substring(0, files[i].length() - 6);
                try {
                    Object o = Class.forName(pckage.getName() + "." + classname).newInstance();
                    if (classType.isInstance(o)) {
                        result.add((E) o);
                    }
                } catch (ClassNotFoundException cnfex) {
                    System.err.println(cnfex);
                } catch (InstantiationException iex) {
                } catch (IllegalAccessException iaex) {
                }
            }
        }
    }
    result.sort(new Comparator<Object>() {
        public int compare(Object o1, Object o2) {
            return o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName());
        }
    });
    return result.toArray((E[]) Array.newInstance(classType, result.size()));
}

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

protected ResultConverter makeResultConveter() {
    ResultConverter converter;/*w w  w  . ja v  a2s. c om*/
    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:com.github.erchu.beancp.MapperImpl.java

private <S> Object[] getArrayOfPrimitiveTypeWrapper(Class sourceClass, final S source)
        throws IllegalArgumentException, NegativeArraySizeException, ArrayIndexOutOfBoundsException {
    Class<?> arrayElementWrapperClass = ClassUtils.primitiveToWrapper(sourceClass.getComponentType());
    int arrayLength = Array.getLength(source);
    Object[] sourceWrapper = (Object[]) Array.newInstance(arrayElementWrapperClass, arrayLength);
    for (int i = 0; i < arrayLength; i++) {
        sourceWrapper[i] = Array.get(source, i);
    }/*ww w .  j a  v  a2  s .  c om*/
    return sourceWrapper;
}

From source file:jp.furplag.util.commons.ObjectUtils.java

/**
 * substitute for {@link java.lang.Class#newInstance()}.
 *
 * @param typeRef {@link com.fasterxml.jackson.core.type.TypeReference}.
 * @return empty instance of specified {@link java.lang.Class}.
 * @throws InstantiationException//w  ww . j  av a2  s .c o  m
 * @throws IllegalAccessException
 * @throws NegativeArraySizeException
 * @throws ClassNotFoundException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws IllegalArgumentException
 * @throws SecurityException
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(TypeReference<T> typeRef) throws InstantiationException {
    if (typeRef == null)
        return null;
    Type type = typeRef.getType();
    if (type instanceof GenericArrayType) {
        Type componentType = ((GenericArrayType) type).getGenericComponentType();
        return (T) Array.newInstance((Class<?>) componentType, 0);
    }
    if (type instanceof ParameterizedType) {
        Type rawType = ((ParameterizedType) type).getRawType();
        Class<?> clazz = (Class<?>) rawType;
        if (clazz.isInterface()) {
            if (List.class.isAssignableFrom(clazz))
                return (T) Lists.newArrayList();
            if (Map.class.isAssignableFrom(clazz))
                return (T) Maps.newHashMap();
            if (Set.class.isAssignableFrom(clazz))
                return (T) Sets.newHashSet();
        }
        try {
            return ((Class<T>) rawType).newInstance();
        } catch (IllegalAccessException e) {
        }

        throw new InstantiationException("could not create instance, the default constructor of \""
                + ((Class<T>) rawType).getName() + "()\" is not accessible ( or undefined ).");
    }
    if (type instanceof Class)
        return newInstance((Class<T>) type);

    return null;
}