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.runwaysdk.generation.loader.RunwayClassLoader.java

/**
 * Loads an array from the base component up. If an array is loaded without
 * its componentType already loaded then an error occurs. Thus it loads from
 * inside out./*from   w  w w .j  a v a2s. c o  m*/
 * 
 * @param arrayType
 */
public static Class<?> loadArray(String arrayType) {
    // Keep track of what types of array we have (an array of Integers and an
    // array of
    // Business objects, for example)
    Stack<String> baseTypes = new Stack<String>();
    String baseType = arrayType;

    Class<?> arrayClass = null;

    // This loop strips the base type out of any n-dimensional array
    while (arrayPattern.matcher(baseType).matches()) {
        if (arrayPrefix.matcher(baseType).matches()) {
            baseType = baseType.replaceFirst("\\[L", "").replace(";", "").trim();
        } else {
            baseType = baseType.replaceFirst("\\[", "");
        }
        // Add the base type to the stack
        baseTypes.push(baseType);
    }

    // We must load all base types before we can try to load arrays of those
    // types
    while (!baseTypes.isEmpty()) {
        String type = baseTypes.pop();
        Class<?> componentType;
        componentType = LoaderDecorator.load(type);
        arrayClass = Array.newInstance(componentType, 0).getClass();
    }
    return arrayClass;
}

From source file:jp.terasoluna.fw.web.struts.form.ValidatorActionFormEx.java

/**
 * wCfbNXuv?peBl??B//from   www.j  a va2  s.  co  m
 *
 * @param name ??CfbNXtv?peB
 * @param index ??CfbNXu
 * @param value ?v?peBl
 */
@SuppressWarnings("unchecked")
public void setIndexedValue(String name, int index, Object value) {
    if (log.isDebugEnabled()) {
        log.debug("set(" + name + ", " + index + ", " + value + ") called.");
    }

    Object prop = null;
    try {
        prop = BeanUtil.getBeanProperty(this, name);
    } catch (PropertyAccessException e) {
        // DynaValidatorActionFormExdl??A
        // O????s?B
    }
    if (prop == null) {
        throw new NullPointerException("No indexed value for '" + name + "[" + index + "]'");
    } else if (prop.getClass().isArray()) {
        if (index < Array.getLength(prop)) {
            Array.set(prop, index, value);
        } else {
            // CfbNX`FbN
            ActionFormUtil.checkIndexLength(index);
            // ?VKz??
            Object newArray = Array.newInstance(prop.getClass().getComponentType(), index + 1);
            // zR|?[lgRs?[
            System.arraycopy(prop, 0, newArray, 0, Array.getLength(prop));
            // R|?[lgZbg
            Array.set(newArray, index, value);
            // Q?Rs?[
            prop = newArray;
        }
        try {
            BeanUtil.setBeanProperty(this, name, prop);
        } catch (PropertyAccessException e) {
            throw new IllegalArgumentException("Cannot set property for '" + name + "[" + index + "]'");
        }
    } else if (prop instanceof List) {
        if (index < ((List) prop).size()) {
            ((List) prop).set(index, value);
        } else {
            // CfbNX`FbN
            ActionFormUtil.checkIndexLength(index);
            Object[] oldValues = ((List) prop).toArray();
            Object[] newValues = (Object[]) Array.newInstance(oldValues.getClass().getComponentType(),
                    index + 1);
            System.arraycopy(oldValues, 0, newValues, 0, oldValues.length);
            newValues[index] = value;
            ((List) prop).clear();
            ((List) prop).addAll(Arrays.asList(newValues));
        }
        try {
            BeanUtil.setBeanProperty(this, name, prop);
        } catch (PropertyAccessException e) {
            throw new IllegalArgumentException("Cannot set property for '" + name + "[" + index + "]'");
        }
    } else {
        throw new IllegalArgumentException("Non-indexed property for '" + name + "[" + index + "]'");
    }

}

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

private static Object parseSingleValue(Class<?> rt, String v, AnnotatedElement anno,
        Map<Class<?>, InputArgParser<?>> inputArgParsers) {
    if (rt.isEnum()) {
        String vlow = v.toLowerCase();
        for (Enum e : rt.asSubclass(Enum.class).getEnumConstants()) {
            if (e.name().toLowerCase().equals(vlow))
                return e;
        }/*  ww w  .  j  a  v a2  s. co m*/
        throw new AssertionError("Enum constant not found: " + v);
    } else if (rt == Integer.class) {
        // map blank strings to null
        return Strings.hasContent(v) ? Integer.valueOf(v) : null;
    } else if (rt == Integer.TYPE) {
        // primitive int must have a value
        return Integer.valueOf(v);
    } else if (rt == Long.class) {
        // map blank strings to null
        return Strings.hasContent(v) ? Long.valueOf(v) : null;
    } else if (rt == Long.TYPE) {
        // primitive long must have a value
        return Long.valueOf(v);
    } else if (rt == Double.class) {
        // map blank strings to null
        return Strings.hasContent(v) ? Double.valueOf(v) : null;
    } else if (rt == Double.TYPE) {
        // primitive double must have a value
        return Double.valueOf(v);
    } else if (rt == String.class) {
        return v;
    } else if (rt.isArray()) {
        Input.List ann = anno.getAnnotation(Input.List.class);
        if (ann == null)
            throw new AssertionError("Array type but no annotation (see " + Input.class + "): " + anno);
        String separator = ann.separator();
        String[] strVals = v.split(separator, -1);
        Class<?> arrayType = rt.getComponentType();
        Object a = Array.newInstance(arrayType, strVals.length);
        for (int i = 0; i < strVals.length; i++) {
            Array.set(a, i, parseSingleValue(arrayType, strVals[i], anno, inputArgParsers));
        }
        return a;
    } else if (inputArgParsers != null) {
        InputArgParser<?> argParser = inputArgParsers.get(rt);
        if (argParser != null) {
            return argParser.parse(v);
        }
    }
    throw new AssertionError("Unknown return type " + rt + " (val: " + v + ")");
}

From source file:com.espertech.esper.event.xml.XPathPropertyGetter.java

private Object castToArray(Object result) {
    if (!(result instanceof NodeList)) {
        return null;
    }/*from   ww w . ja  v a 2 s  . c  o m*/

    NodeList nodeList = (NodeList) result;
    Object array = Array.newInstance(optionalCastToType, nodeList.getLength());

    for (int i = 0; i < nodeList.getLength(); i++) {
        Object arrayItem = null;
        try {
            Node item = nodeList.item(i);
            String textContent;
            if ((item.getNodeType() == Node.ATTRIBUTE_NODE) || (item.getNodeType() == Node.ELEMENT_NODE)) {
                textContent = nodeList.item(i).getTextContent();
            } else {
                continue;
            }

            arrayItem = simpleTypeParser.parse(textContent);
        } catch (Exception ex) {
            if (log.isInfoEnabled()) {
                log.info("Parse error for text content " + nodeList.item(i).getTextContent()
                        + " for expression " + expression);
            }
        }
        Array.set(array, i, arrayItem);
    }

    return array;
}

From source file:com.jeeframework.util.classes.ClassUtils.java

/**
 * Replacement for <code>Class.forName()</code> that also returns Class instances
 * for primitives (like "int") and array class names (like "String[]").
 * @param name the name of the Class// w w  w  . j  av  a2s. co m
 * @param classLoader the class loader to use
 * (may be <code>null</code>, 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) {
        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
    int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX);
    if (internalArrayMarker != -1 && name.endsWith(";")) {
        String elementClassName = null;
        if (internalArrayMarker == 0) {
            elementClassName = name.substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1);
        } else if (name.startsWith("[")) {
            elementClassName = name.substring(1);
        }
        Class elementClass = forName(elementClassName, classLoader);
        return Array.newInstance(elementClass, 0).getClass();
    }

    ClassLoader classLoaderToUse = classLoader;
    if (classLoaderToUse == null) {
        classLoaderToUse = getDefaultClassLoader();
    }
    return classLoaderToUse.loadClass(name);
}

From source file:com.espertech.esper.epl.annotation.AnnotationUtil.java

private static Object getFinalValue(Class annotationClass, AnnotationAttribute annotationAttribute,
        Object value, EngineImportService engineImportService) throws AnnotationException {
    if (value == null) {
        if (annotationAttribute.getDefaultValue() == null) {
            throw new AnnotationException("Annotation '" + annotationClass.getSimpleName()
                    + "' requires a value for attribute '" + annotationAttribute.getName() + "'");
        }/*from w w  w. j a  va  2s .  co  m*/
        return annotationAttribute.getDefaultValue();
    }

    // handle non-array
    if (!annotationAttribute.getType().isArray()) {
        // handle primitive value
        if (!annotationAttribute.getType().isAnnotation()) {
            SimpleTypeCaster caster = SimpleTypeCasterFactory.getCaster(value.getClass(),
                    annotationAttribute.getType());
            Object finalValue = caster.cast(value);
            if (finalValue == null) {
                throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a "
                        + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '"
                        + annotationAttribute.getName() + "' but received " + "a "
                        + value.getClass().getSimpleName() + "-typed value");
            }
            return finalValue;
        } else {
            // nested annotation
            if (!(value instanceof AnnotationDesc)) {
                throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a "
                        + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '"
                        + annotationAttribute.getName() + "' but received " + "a "
                        + value.getClass().getSimpleName() + "-typed value");
            }
            return createProxy((AnnotationDesc) value, engineImportService);
        }
    }

    if (!value.getClass().isArray()) {
        throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a "
                + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '"
                + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName()
                + "-typed value");
    }

    Object array = Array.newInstance(annotationAttribute.getType().getComponentType(), Array.getLength(value));
    for (int i = 0; i < Array.getLength(value); i++) {
        Object arrayValue = Array.get(value, i);
        if (arrayValue == null) {
            throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a "
                    + "non-null value for array elements for attribute '" + annotationAttribute.getName()
                    + "'");
        }
        SimpleTypeCaster caster = SimpleTypeCasterFactory.getCaster(arrayValue.getClass(),
                annotationAttribute.getType().getComponentType());
        Object finalValue = caster.cast(arrayValue);
        if (finalValue == null) {
            throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a "
                    + annotationAttribute.getType().getComponentType().getSimpleName()
                    + "-typed value for array elements for attribute '" + annotationAttribute.getName()
                    + "' but received " + "a " + arrayValue.getClass().getSimpleName() + "-typed value");
        }
        Array.set(array, i, finalValue);
    }
    return array;
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private Object doConvertToArray(Map<String, Object> context, Object o, Member member, String s, Object value,
        Class toType) {//from  ww  w .j  a v a  2 s. c om
    Object result = null;
    Class componentType = toType.getComponentType();

    if (componentType != null) {
        TypeConverter converter = getTypeConverter(context);

        if (value.getClass().isArray()) {
            int length = Array.getLength(value);
            result = Array.newInstance(componentType, length);

            for (int i = 0; i < length; i++) {
                Object valueItem = Array.get(value, i);
                Array.set(result, i, converter.convertValue(context, o, member, s, valueItem, componentType));
            }
        } else {
            result = Array.newInstance(componentType, 1);
            Array.set(result, 0, converter.convertValue(context, o, member, s, value, componentType));
        }
    }

    return result;
}

From source file:ArraysX.java

/**
 * Resizes the specified array. Similar to {@link #shrink}, but
 * it can enlarge and it keeps elements from the first.
 *///from w  w w.  jav  a  2s.c  o m
public static final Object resize(Object ary, int size) {
    final int oldsz = Array.getLength(ary);
    if (oldsz == size)
        return ary;

    final Object dst = Array.newInstance(ary.getClass().getComponentType(), size);
    System.arraycopy(ary, 0, dst, 0, oldsz > size ? size : oldsz);
    return dst;
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.java

/**
 * Given an object extracted from JSONObject field, convert it to an
 * appropriate object with type appropriate for given type so that it can be
 * assigned to the associated field of the ummarshalled object. eg.
 * JSONObject value from a JSONObject field probably needs to be
 * unmarshalled to a class instance. Double from JSONObject may need to be
 * converted to Float. etc./*from www  .  ja  v a 2  s .com*/
 *
 * @param val Value extracted from JSONObject field.
 * @param genericType Type to convert to. Must be generic type. ie. From
 *                    field.getGenericType().
 * @return Object of the given type so it can be assinged to field with
 * field.set().
 * @throws com.initialxy.cordova.themeablebrowser.ThemeableBrowserUnmarshaller.TypeMismatchException
 */
private static Object valToType(Object val, Type genericType) {
    Object result = null;
    boolean isArray = false;

    Class<?> rawType = null;
    if (genericType instanceof ParameterizedType) {
        rawType = (Class<?>) ((ParameterizedType) genericType).getRawType();
    } else if (genericType instanceof GenericArrayType) {
        rawType = List.class;
        isArray = true;
    } else {
        rawType = (Class<?>) genericType;
    }

    isArray = isArray || rawType.isArray();

    if (val != null && val != JSONObject.NULL) {
        if (rawType.isAssignableFrom(String.class)) {
            if (val instanceof String) {
                result = val;
            } else {
                throw new TypeMismatchException(rawType, val.getClass());
            }
        } else if (isPrimitive(rawType)) {
            result = convertToPrimitiveFieldObj(val, rawType);
        } else if (isArray || rawType.isAssignableFrom(List.class)) {
            if (val instanceof JSONArray) {
                Type itemType = getListItemType(genericType);
                result = JSONToList((JSONArray) val, itemType);

                if (isArray) {
                    List<?> list = (List<?>) result;

                    Class<?> itemClass = null;
                    if (itemType instanceof ParameterizedType) {
                        itemClass = (Class<?>) ((ParameterizedType) itemType).getRawType();
                    } else {
                        itemClass = (Class<?>) itemType;
                    }

                    result = Array.newInstance(itemClass, list.size());
                    int cnt = 0;
                    for (Object i : list) {
                        Array.set(result, cnt, i);
                        cnt += 1;
                    }
                }
            } else {
                throw new TypeMismatchException(JSONArray.class, val.getClass());
            }
        } else if (val instanceof JSONObject) {
            result = JSONToObj((JSONObject) val, rawType);
        }
    }

    return result;
}

From source file:com.vk.sdk.api.model.ParseUtils.java

/**
 * Parses array from given JSONArray./*from ww w. j  ava2 s.c  om*/
 * Supports parsing of primitive types and {@link com.vk.sdk.api.model.VKApiModel} instances.
 * @param array JSONArray to parse
 * @param arrayClass type of array field in class.
 * @return object to set to array field in class
 * @throws JSONException if given array have incompatible type with given field.
 */
private static Object parseArrayViaReflection(JSONArray array, Class arrayClass) throws JSONException {
    Object result = Array.newInstance(arrayClass.getComponentType(), array.length());
    Class<?> subType = arrayClass.getComponentType();
    for (int i = 0; i < array.length(); i++) {
        try {
            Object item = array.opt(i);
            if (VKApiModel.class.isAssignableFrom(subType) && item instanceof JSONObject) {
                VKApiModel model = (VKApiModel) subType.newInstance();
                item = model.parse((JSONObject) item);
            }
            Array.set(result, i, item);
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalArgumentException e) {
            throw new JSONException(e.getMessage());
        }
    }
    return result;
}