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:com.dianping.resource.io.util.ClassUtils.java

/**
 * Replacement for {@code Class.forName()} that also returns Class instances
 * for primitives (e.g. "int") and array class names (e.g. "String[]").
 * Furthermore, it is also capable of resolving inner class names in Java source
 * style (e.g. "java.lang.Thread.State" instead of "java.lang.Thread$State").
 * @param name the name of the Class/*  w w  w .  j a v a 2s . co m*/
 * @param classLoader the class loader to use
 * (may be {@code null}, which indicates the default class loader)
 * @return Class instance for the supplied name
 * @throws ClassNotFoundException if the class was not found
 * @throws LinkageError if the class file could not be loaded
 * @see Class#forName(String, boolean, ClassLoader)
 */
public static Class<?> forName(String name, ClassLoader classLoader)
        throws ClassNotFoundException, LinkageError {
    Assert.notNull(name, "Name must not be null");

    Class<?> clazz = resolvePrimitiveClassName(name);
    if (clazz == null) {
        clazz = commonClassCache.get(name);
    }
    if (clazz != null) {
        return clazz;
    }

    // "java.lang.String[]" style arrays
    if (name.endsWith(ARRAY_SUFFIX)) {
        String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
        Class<?> elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[Ljava.lang.String;" style arrays
    if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
        String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[[I" or "[[Ljava.lang.String;" style arrays
    if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
        String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    ClassLoader clToUse = classLoader;
    if (clToUse == null) {
        clToUse = getDefaultClassLoader();
    }
    try {
        return (clToUse != null ? clToUse.loadClass(name) : Class.forName(name));
    } catch (ClassNotFoundException ex) {
        int lastDotIndex = name.lastIndexOf('.');
        if (lastDotIndex != -1) {
            String innerClassName = name.substring(0, lastDotIndex) + '$' + name.substring(lastDotIndex + 1);
            try {
                return (clToUse != null ? clToUse.loadClass(innerClassName) : Class.forName(innerClassName));
            } catch (ClassNotFoundException ex2) {
                // swallow - let original exception get through
            }
        }
        throw ex;
    }
}

From source file:com.freetmp.common.util.ClassUtils.java

public static Class<?> forName(String name, ClassLoader classLoader)
        throws ClassNotFoundException, LinkageError {
    Assert.notNull(name, "Name must not be null");

    Class<?> clazz = resolvePrimitiveClassName(name);
    if (clazz == null) {
        clazz = commonClassCache.get(name);
    }/*from w  w w  .ja  v a 2 s.  com*/
    if (clazz != null) {
        return clazz;
    }

    // "java.lang.String[]" style arrays
    if (name.endsWith(ARRAY_SUFFIX)) {
        String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
        Class<?> elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[Ljava.lang.String;" style arrays
    if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
        String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[[I" or "[[Ljava.lang.String;" style arrays
    if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
        String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    ClassLoader clToUse = classLoader;
    if (clToUse == null) {
        clToUse = getDefaultClassLoader();
    }
    try {
        return (clToUse != null ? clToUse.loadClass(name) : Class.forName(name));
    } catch (ClassNotFoundException ex) {
        int lastDotIndex = name.lastIndexOf(PACKAGE_SEPARATOR);
        if (lastDotIndex != -1) {
            String innerClassName = name.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR
                    + name.substring(lastDotIndex + 1);
            try {
                return (clToUse != null ? clToUse.loadClass(innerClassName) : Class.forName(innerClassName));
            } catch (ClassNotFoundException ex2) {
                // Swallow - let original exception get through
            }
        }
        throw ex;
    }
}

From source file:com.astamuse.asta4d.data.DefaultDataTypeTransformer.java

private List<DataValueConvertor> extractConvertors(final Class<?> srcType, final Class<?> targetType) {

    List<DataValueConvertor> foundConvertorList = new LinkedList<DataValueConvertor>();

    // find in list as element to element
    for (DataValueConvertor convertor : DataTypeConvertorList) {
        Pair<Class, Class> typePair = extractConvertorTypeInfo(convertor);
        if (typePair == null) {
            continue;
        }// ww  w.j  a va 2s . c o  m
        if (typePair.getLeft().isAssignableFrom(srcType)) {
            if (targetType.isAssignableFrom(typePair.getRight())) {// found one
                foundConvertorList.add(convertor);
            } else if (convertor instanceof DataValueConvertorTargetTypeConvertable
                    && typePair.getRight().isAssignableFrom(targetType)) {
                foundConvertorList
                        .add(((DataValueConvertorTargetTypeConvertable) convertor).convert(targetType));
            }
        }
        // @formatter:on
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as array to array
    if (srcType.isArray() && targetType.isArray()) {

        List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(),
                targetType.getComponentType());
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor);

                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                if (typePair == null) {
                                    return null;
                                }

                                int length = Array.getLength(obj);
                                Object targetArray = Array.newInstance(targetType.getComponentType(), length);

                                for (int i = 0; i < length; i++) {
                                    Array.set(targetArray, i, originalConvertor.convert(Array.get(obj, i)));
                                }
                                return targetArray;
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as element to array
    if (targetType.isArray()) {

        List<DataValueConvertor> componentConvertorList = findConvertor(srcType, targetType.getComponentType());
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            private Pair<Class, Class> typePair = extractConvertorTypeInfo(originalConvertor);

                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                if (typePair == null) {
                                    return null;
                                }
                                Object array = Array.newInstance(targetType.getComponentType(), 1);
                                Array.set(array, 0, originalConvertor.convert(obj));
                                return array;
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    // find as array to element
    if (srcType.isArray()) {
        List<DataValueConvertor> componentConvertorList = findConvertor(srcType.getComponentType(), targetType);
        List<DataValueConvertor> toArrayConvertorList = ListConvertUtil.transform(componentConvertorList,
                new RowConvertor<DataValueConvertor, DataValueConvertor>() {
                    @Override
                    public DataValueConvertor convert(int rowIndex,
                            final DataValueConvertor originalConvertor) {
                        return new DataValueConvertor() {
                            @Override
                            public Object convert(Object obj) throws UnsupportedValueException {
                                int length = Array.getLength(obj);
                                if (length == 0) {
                                    return null;
                                } else {
                                    return originalConvertor.convert(Array.get(obj, 0));
                                }
                            }
                        };
                    }
                });

        foundConvertorList.addAll(toArrayConvertorList);
    }

    if (!foundConvertorList.isEmpty()) {
        return foundConvertorList;
    }

    return foundConvertorList;
}

From source file:ArraysX.java

/** Clones an array.
 *///from  www . j a va 2 s.  c  om
public static final Object clone(Object ary) {
    final int size = Array.getLength(ary);
    final Object dst = Array.newInstance(ary.getClass().getComponentType(), size);
    System.arraycopy(ary, 0, dst, 0, size);
    return dst;
}

From source file:org.dkpro.lab.Util.java

public static void createSymbolicLink(File aSource, File aTarget) throws IOException {
    if (aTarget.exists()) {
        throw new FileExistsException(aTarget);
    }//from   www.ja v  a  2s.  c  o m

    File parentDir = aTarget.getAbsoluteFile().getParentFile();
    if (parentDir != null && !parentDir.exists()) {
        FileUtils.forceMkdir(parentDir);
    }

    // Try Java 7 methods
    try {
        Object fromPath = MethodUtils.invokeExactMethod(aSource, "toPath", new Object[0]);
        Object toPath = MethodUtils.invokeExactMethod(aTarget, "toPath", new Object[0]);
        Object options = Array.newInstance(Class.forName("java.nio.file.attribute.FileAttribute"), 0);
        MethodInvoker inv = new MethodInvoker();
        inv.setStaticMethod("java.nio.file.Files.createSymbolicLink");
        inv.setArguments(new Object[] { toPath, fromPath, options });
        inv.prepare();
        inv.invoke();
        return;
    } catch (ClassNotFoundException e) {
        // Ignore
    } catch (NoSuchMethodException e) {
        // Ignore
    } catch (IllegalAccessException e) {
        // Ignore
    } catch (InvocationTargetException e) {
        if ("java.nio.file.FileAlreadyExistsException".equals(e.getTargetException().getClass().getName())) {
            throw new FileExistsException(aTarget);
        }
    }

    // If the Java 7 stuff is not available, fall back to Runtime.exec
    String[] cmdline = { "ln", "-s", aSource.getAbsolutePath(), aTarget.getAbsolutePath() };
    Execute exe = new Execute();
    exe.setVMLauncher(false);
    exe.setCommandline(cmdline);
    exe.execute();
    if (exe.isFailure()) {
        throw new IOException("Unable to create symlink from [" + aSource + "] to [" + aTarget + "]");
    }
}

From source file:ArrayUtils.java

/**
 * Merges all elements of a set of arrays into a single array with no
 * duplicates. For primitive types./*  w  w w  .  java 2 s  .c  om*/
 * 
 * @param type
 *            The type of the result
 * @param arrays
 *            The arrays to merge
 * @return A new array containing all elements of <code>array1</code> and
 *         all elements of <code>array2</code> that are not present in
 *         <code>array1</code>
 * @throws NullPointerException
 *             If either array is null
 * @throws ArrayStoreException
 *             If elements in the arrays are incompatible with
 *             <code>type</code>
 */
public static Object mergeInclusiveP(Class<?> type, Object... arrays) {
    java.util.LinkedHashSet<Object> set = new java.util.LinkedHashSet<Object>();
    int i, j;
    for (i = 0; i < arrays.length; i++) {
        int len = Array.getLength(arrays[i]);
        for (j = 0; j < len; j++)
            set.add(Array.get(arrays[i], j));
    }
    Object ret = Array.newInstance(type, set.size());
    i = 0;
    for (Object el : set) {
        put(ret, el, i);
        i++;
    }
    return ret;
}

From source file:org.crazydog.util.spring.ClassUtils.java

/**
 * Replacement for {@code Class.forName()} that also returns Class instances
 * for primitives (e.g. "int") and array class names (e.g. "String[]").
 * Furthermore, it is also capable of resolving inner class names in Java source
 * style (e.g. "java.lang.Thread.State" instead of "java.lang.Thread$State").
 * @param name the name of the Class/*w w  w.j a  va2  s .c  o m*/
 * @param classLoader the class loader to use
 * (may be {@code null}, which indicates the default class loader)
 * @return Class instance for the supplied name
 * @throws ClassNotFoundException if the class was not found
 * @throws LinkageError if the class file could not be loaded
 * @see Class#forName(String, boolean, ClassLoader)
 */
public static Class<?> forName(String name, ClassLoader classLoader)
        throws ClassNotFoundException, LinkageError {
    org.springframework.util.Assert.notNull(name, "Name must not be null");

    Class<?> clazz = resolvePrimitiveClassName(name);
    if (clazz == null) {
        clazz = commonClassCache.get(name);
    }
    if (clazz != null) {
        return clazz;
    }

    // "java.lang.String[]" style arrays
    if (name.endsWith(ARRAY_SUFFIX)) {
        String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length());
        Class<?> elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[Ljava.lang.String;" style arrays
    if (name.startsWith(NON_PRIMITIVE_ARRAY_PREFIX) && name.endsWith(";")) {
        String elementName = name.substring(NON_PRIMITIVE_ARRAY_PREFIX.length(), name.length() - 1);
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    // "[[I" or "[[Ljava.lang.String;" style arrays
    if (name.startsWith(INTERNAL_ARRAY_PREFIX)) {
        String elementName = name.substring(INTERNAL_ARRAY_PREFIX.length());
        Class<?> elementClass = forName(elementName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    ClassLoader clToUse = classLoader;
    if (clToUse == null) {
        clToUse = getDefaultClassLoader();
    }
    try {
        return (clToUse != null ? clToUse.loadClass(name) : Class.forName(name));
    } catch (ClassNotFoundException ex) {
        int lastDotIndex = name.lastIndexOf(PACKAGE_SEPARATOR);
        if (lastDotIndex != -1) {
            String innerClassName = name.substring(0, lastDotIndex) + INNER_CLASS_SEPARATOR
                    + name.substring(lastDotIndex + 1);
            try {
                return (clToUse != null ? clToUse.loadClass(innerClassName) : Class.forName(innerClassName));
            } catch (ClassNotFoundException ex2) {
                // Swallow - let original exception get through
            }
        }
        throw ex;
    }
}

From source file:com.icesoft.faces.renderkit.dom_html_basic.MenuRenderer.java

protected Object convertArray(FacesContext facesContext, UISelectMany uiSelectMany, Class componentType,
        String[] newSubmittedValues) throws ConverterException {

    // component type of String means no conversion is necessary
    if (componentType.equals(String.class)) {
        return newSubmittedValues;
    }//from   w w  w . j av a  2s  .c  o  m

    // if newSubmittedValue is null return zero-length array
    if (newSubmittedValues == null) {
        return Array.newInstance(componentType, 0);
    }

    // create the array with specified component length
    int numberOfValues = newSubmittedValues.length;
    Object convertedValues = Array.newInstance(componentType, numberOfValues);

    // Determine if a converter is explicitly registered with the component
    Converter converter = uiSelectMany.getConverter();
    if (converter == null) {
        // Determine if there is a default converter for the class
        converter = getConverterForClass(componentType);
    }
    if (converter == null) {
        // we don't need to convert base Object types
        if (componentType.equals(Object.class)) {
            return newSubmittedValues;
        } else {
            throw new ConverterException("Converter is null");
        }
    }

    for (int index = 0; index < numberOfValues; index++) {

        // convert the next element
        Object nextConvertedElement = converter.getAsObject(facesContext, uiSelectMany,
                newSubmittedValues[index]);

        if (!componentType.isPrimitive()) {
            Array.set(convertedValues, index, nextConvertedElement);
        } else if (componentType.equals(Boolean.TYPE)) {

            Array.setBoolean(convertedValues, index, ((Boolean) nextConvertedElement).booleanValue());

        } else if (componentType.equals(Integer.TYPE)) {

            Array.setInt(convertedValues, index, ((Integer) nextConvertedElement).intValue());

        } else if (componentType.equals(Long.TYPE)) {

            Array.setLong(convertedValues, index, ((Long) nextConvertedElement).longValue());

        } else if (componentType.equals(Short.TYPE)) {

            Array.setShort(convertedValues, index, ((Short) nextConvertedElement).shortValue());

        } else if (componentType.equals(Byte.TYPE)) {

            Array.setByte(convertedValues, index, ((Byte) nextConvertedElement).byteValue());

        } else if (componentType.equals(Float.TYPE)) {

            Array.setFloat(convertedValues, index, ((Float) nextConvertedElement).floatValue());

        } else if (componentType.equals(Double.TYPE)) {

            Array.setDouble(convertedValues, index, ((Double) nextConvertedElement).doubleValue());

        } else if (componentType.equals(Character.TYPE)) {

            Array.setChar(convertedValues, index, ((Character) nextConvertedElement).charValue());

        }
    }
    return convertedValues;
}

From source file:ipc.WritableRpcEngine.java

/** Expert: Make multiple, parallel calls to a set of servers. */
public Object[] call(Method method, Object[][] params, InetSocketAddress[] addrs, Configuration conf)
        throws IOException, InterruptedException {

    Invocation[] invocations = new Invocation[params.length];
    for (int i = 0; i < params.length; i++)
        invocations[i] = new Invocation(method, params[i]);
    Client client = CLIENTS.getClient(conf);
    try {//from   w  w w  .  j ava  2  s  .co m
        Writable[] wrappedValues = client.call(invocations, addrs, method.getDeclaringClass());

        if (method.getReturnType() == Void.TYPE) {
            return null;
        }

        Object[] values = (Object[]) Array.newInstance(method.getReturnType(), wrappedValues.length);
        for (int i = 0; i < values.length; i++)
            if (wrappedValues[i] != null)
                values[i] = ((ObjectWritable) wrappedValues[i]).get();

        return values;
    } finally {
        CLIENTS.stopClient(client);
    }
}

From source file:net.jodah.typetools.TypeResolver.java

private static Class<?> resolveRawClass(Type genericType, Class<?> subType, Class<?> functionalInterface) {
    if (genericType instanceof Class) {
        return (Class<?>) genericType;
    } else if (genericType instanceof ParameterizedType) {
        return resolveRawClass(((ParameterizedType) genericType).getRawType(), subType, functionalInterface);
    } else if (genericType instanceof GenericArrayType) {
        GenericArrayType arrayType = (GenericArrayType) genericType;
        Class<?> compoment = resolveRawClass(arrayType.getGenericComponentType(), subType, functionalInterface);
        return Array.newInstance(compoment, 0).getClass();
    } else if (genericType instanceof TypeVariable) {
        TypeVariable<?> variable = (TypeVariable<?>) genericType;
        genericType = getTypeVariableMap(subType, functionalInterface).get(variable);
        genericType = genericType == null ? resolveBound(variable)
                : resolveRawClass(genericType, subType, functionalInterface);
    }//from w  w w .  j a v a  2  s  . c  o m

    return genericType instanceof Class ? (Class<?>) genericType : Unknown.class;
}