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.amazonaws.mturk.service.axis.AWSService.java

/**
 * /*from  ww w.jav  a2  s  . c  om*/
 * @param m - Message structure which contains the details for making wsdl operation call 
 * @return Reply structure containing results and errors from the wsdl operation call 
 * @throws ServiceException
 */
public Reply executeRequestMessage(Message m) throws ServiceException {
    String axisMethodName = m.getMethodName();
    Object requests = m.getRequests();
    String credential = m.getCredential();
    String resultAccessorName = m.getResultAccessorName();
    try {
        Class bodyClass;
        Class responseClass;
        Class requestClass;
        Object body;

        // Construct the request body
        bodyClass = Class.forName(getPackagePrefix() + axisMethodName);
        body = bodyClass.newInstance();

        responseClass = Class.forName(getPackagePrefix() + axisMethodName + RESPONSE_SUFFIX);
        requestClass = Class.forName(getPackagePrefix() + axisMethodName + REQUEST_SUFFIX);

        Class requestArrayClass = Array.newInstance(requestClass, 0).getClass();
        Object requestArray = requestArrayClass.cast(requests);

        Method setRequest = bodyClass.getMethod(SET_REQUEST_METHOD_NAME, new Class[] { requestArrayClass });
        setRequest.invoke(body, requestArray);

        Calendar now = null;
        String signature = null;

        synchronized (AWSService.class) {
            Method setAWSAccessKeyId = bodyClass.getMethod(SET_AWS_ACCESS_KEY_ID_METHOD_NAME,
                    STRING_CLASS_ARRAY);
            setAWSAccessKeyId.invoke(body, getAWSAccessKeyId());

            Method setValidate = bodyClass.getMethod(SET_VALIDATE_METHOD_NAME, STRING_CLASS_ARRAY);
            setValidate.invoke(body, (Object) null);

            if (credential != null && credential.length() > 0) {
                Method setCredential = bodyClass.getMethod(SET_CREDENTIAL_METHOD_NAME, STRING_CLASS_ARRAY);
                setCredential.invoke(body, credential);
            }

            Method setTimestamp = bodyClass.getMethod(SET_TIMESTAMP_METHOD_NAME, CALENDAR_CLASS_ARRAY);
            now = Calendar.getInstance();
            setTimestamp.invoke(body, now);

            // Create the signature
            Method setSignature = bodyClass.getMethod(SET_SIGNATURE_METHOD_NAME, STRING_CLASS_ARRAY);
            signature = getSigner().sign(getServiceName(), axisMethodName, now);

            setSignature.invoke(body, signature);
        }

        Object response = responseClass.newInstance();

        String axisClassMethodName = axisMethodName.substring(0, 1).toLowerCase() + axisMethodName.substring(1);
        Method axisMethod = getPort().getClass().getMethod(axisClassMethodName, new Class[] { bodyClass });

        try {
            // Execute the request and get a response
            response = axisMethod.invoke(getPort(), body);
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof AxisFault) {
                //errors due to throttling are inside AxisFault. Get those if present
                AxisFault fault = (AxisFault) e.getCause();

                String httpResponse = fault.getFaultCode().getLocalPart();
                List<String> errorCodes = new ArrayList<String>();
                errorCodes.add(httpResponse);

                // When Axis encounters networking errors, it sets the fault code to
                // {http://xml.apache.org/axis/}HTTP
                // In this case it sets the error code from the http response in
                // the "HttpErrorCode" element of the fault details
                // If this is the case, add it to the error codes so the SDK
                // can be configured to retry for specific response codes
                if (AXIS_HTTP_FAULT.equals(fault.getFaultCode())) {
                    Element faultElement = fault.lookupFaultDetail(AXIS_HTTP_ERROR_CODE);
                    if (faultElement != null && faultElement.getFirstChild() != null) {
                        errorCodes.add(faultElement.getFirstChild().getNodeValue());
                    }
                }

                throw new InternalServiceException(e.getCause(), errorCodes);
            }
            throw new ServiceException(e.getCause());
        }

        // Extract the Operation Request
        Method getOperationRequest = responseClass.getMethod(GET_OPERATION_REQUEST_METHOD_NAME);
        Object operationRequest = getOperationRequest.invoke(response);

        // Extract the Errors
        Method getErrors = operationRequest.getClass().getMethod(GET_ERRORS_METHOD_NAME);
        Object errors = getErrors.invoke(operationRequest);
        Object[] results = null;

        if (errors != null) {
            return new Reply(results, errors, getRequestId(operationRequest));
        }

        Method getResult = responseClass.getMethod(GET_PREFIX + resultAccessorName);
        results = (Object[]) getResult.invoke(response);

        if (results == null || results.length == 0) {
            throw new ServiceException("Empty result, unknown error.");
        }

        for (int i = 0; i < results.length; i++) {
            Object result = results[i];

            Method getRequest = result.getClass().getMethod(GET_REQUEST_METHOD_NAME);
            Object request = getRequest.invoke(result);

            getErrors = request.getClass().getMethod(GET_ERRORS_METHOD_NAME);
            errors = getErrors.invoke(request);

            if (errors != null) {
                break; //get only the first error
            }
        }
        return new Reply(results, errors, getRequestId(operationRequest));

    } catch (ClassNotFoundException e) {
        throw new ServiceException(e);
    } catch (IllegalAccessException e) {
        throw new ServiceException(e);
    } catch (InstantiationException e) {
        throw new ServiceException(e);
    } catch (NoSuchMethodException e) {
        throw new ServiceException(e);
    } catch (InvocationTargetException e) {
        throw new ServiceException(e.getCause());
    }
}

From source file:hu.javaforum.commons.ReflectionHelper.java

/**
 * Creates a parameter from the value. If the value instance of String then
 * this method calls the converter methods.
 *
 * @param fieldClass The class of field//  www.  j  av a 2  s.  co m
 * @param value The value
 * @return The converted instance
 * @throws ClassNotFoundException If class not found
 * @throws ParseException If the pattern cannot be parseable
 * @throws UnsupportedEncodingException If the Base64 stream contains non UTF-8 chars
 */
protected static Object createParameterFromValue(final Class fieldClass, final Object value)
        throws ClassNotFoundException, ParseException, UnsupportedEncodingException {
    Object parameter = value;

    if (!value.getClass().equals(fieldClass) && !PRIMITIVE_WRAPPER_CLASSES.contains(value.getClass())) {
        if (fieldClass.isArray() && value instanceof List) {
            String arrayElementTypeName = fieldClass.getName().substring(2, fieldClass.getName().length() - 1);
            Class arrayElementType = Class.forName(arrayElementTypeName);
            Object[] at = (Object[]) Array.newInstance(arrayElementType, 0);
            parameter = ((List<Object>) value).toArray(at);
        } else {
            String stringValue = createStringFromValue(value);
            if (stringValue != null) {
                parameter = convertToPrimitive(fieldClass, stringValue);
                parameter = parameter == null ? convertToPrimitiveWrapper(fieldClass, stringValue) : parameter;
                parameter = parameter == null ? convertToBigNumbers(fieldClass, stringValue) : parameter;
                parameter = parameter == null ? convertToOthers(fieldClass, stringValue) : parameter;
            }
        }
    }

    return parameter;
}

From source file:com.github.cherimojava.data.mongo.entity.EntityUtils.java

/**
 * returns the adder method matching the given Getter method or throws an exception if no such method exists
 *
 * @param m getter method for which a matching adder method shall be found
 * @return adder method belongign to the given Getter method
 * @throws java.lang.IllegalArgumentException if the given method has no matching adder method
 *//*from  ww  w. j  a v  a2 s  .c om*/
static Method getAdderFromGetter(Method m) {
    try {
        return m.getDeclaringClass().getMethod(m.getName().replaceFirst("get", "add"),
                (Class) ((ParameterizedType) m.getGenericReturnType()).getActualTypeArguments()[0]);
    } catch (Exception e) {
        try {
            // if we had no hit, try if there's a vararg adder
            return m.getDeclaringClass().getMethod(m.getName().replaceFirst("get", "add"),
                    Array.newInstance(
                            (Class) ((ParameterizedType) m.getGenericReturnType()).getActualTypeArguments()[0],
                            0).getClass());
        } catch (Exception e1) {
            throw new IllegalArgumentException(
                    format("Method %s has no corresponding adder method", m.getName()));
        }
    }
}

From source file:egovframework.rte.itl.webservice.service.impl.EgovWebServiceClassLoaderImpl.java

public Class<?> loadClass(final Type type) throws ClassNotFoundException {
    LOG.debug("loadClass of Type (" + type + ")");

    if (type == EgovWebServiceMessageHeader.TYPE) {
        LOG.debug("Type is EgovWebServiceMessageHeader.");
        return EgovWebServiceMessageHeader.class;
    }/* w ww .  j  a  v a2 s  .c o  m*/

    if (type instanceof PrimitiveType) {
        LOG.debug("Type is a Primitive Type");
        Class<?> clazz = primitiveClasses.get((PrimitiveType) type);
        if (clazz == null) {
            LOG.error("No such primitive type");
            throw new ClassNotFoundException();
        }
        return clazz;
    } else if (type instanceof ListType) {
        LOG.debug("Type is a List Type");
        ListType listType = (ListType) type;
        Class<?> elementClass = loadClass(listType.getElementType());

        return Array.newInstance(elementClass, 0).getClass();
    } else if (type instanceof RecordType) {
        LOG.debug("Type is a Record Type");

        RecordType recordType = (RecordType) type;

        String className = getRecordTypeClassName(recordType.getName());
        try {
            LOG.debug("Check the class \"" + className + "\" is already loaded.");
            return loadClass(className);
        } catch (ClassNotFoundException e) {
            LOG.debug("Create a new class \"" + className + "\"");
            byte[] byteCode = createRecordClass(className, recordType);
            return defineClass(className, byteCode, 0, byteCode.length);
        }
    }
    LOG.error("Type is invalid");
    throw new ClassNotFoundException();
}

From source file:Main.java

/**
 * Ensures the given array has a given size.
 * @param array the array./*from w  w w .  j av  a  2s.  c  o  m*/
 * @param size  the target size of the array.
 * @return      the original array, or a copy if it had to be extended.
 */
public static Object[] extendArray(Object[] array, int size) {
    // Reuse the existing array if possible.
    if (array.length >= size) {
        return array;
    }

    // Otherwise create and initialize a new array.
    Object[] newArray = (Object[]) Array.newInstance(array.getClass().getComponentType(), size);

    System.arraycopy(array, 0, newArray, 0, array.length);

    return newArray;
}

From source file:com.evolveum.midpoint.prism.PrismProperty.java

/**
  * Type override, also for compatibility.
  */// w  w w . ja v a  2 s .co  m
public <X> X[] getRealValuesArray(Class<X> type) {
    X[] valuesArrary = (X[]) Array.newInstance(type, getValues().size());
    for (int j = 0; j < getValues().size(); ++j) {
        Object avalue = getValues().get(j).getValue();
        Array.set(valuesArrary, j, avalue);
    }
    return valuesArrary;
}

From source file:com.linkedin.drelephant.math.Statistics.java

public static <T> T[] createSample(Class<T> clazz, T[] objects, int size) {
    //Skip this process if number of items already smaller than sample size
    if (objects.length <= size) {
        return objects;
    }//  ww w  .j a  va 2 s.c om

    @SuppressWarnings("unchecked")
    T[] result = (T[]) Array.newInstance(clazz, size);

    //Shuffle a clone copy
    T[] clone = objects.clone();
    Collections.shuffle(Arrays.asList(clone));

    //Take the first n items
    System.arraycopy(clone, 0, result, 0, size);

    return result;
}

From source file:org.t2framework.commons.util.ArrayMap.java

 public final Object[] toArray(final Object proto[]) {
   Object[] array = proto;//from   w  w  w.ja v  a  2s. c  o m
   if (proto.length < size) {
      array = (Object[]) Array.newInstance(proto.getClass()
            .getComponentType(), size);
   }
   for (int i = 0; i < array.length; i++) {
      array[i] = get(i);
   }
   if (array.length > size) {
      array[size] = null;
   }
   return array;
}

From source file:com.ocpsoft.pretty.faces.el.resolver.CDIBeanNameResolver.java

public String getBeanName(Class<?> clazz) {
    // catch reflection exceptions
    try {/*from ww w . j  a  v  a2 s .  c  o  m*/

        // call BeanManager.getBeans(clazz) without suppling qualifiers
        Set<?> beansSet = (Set<?>) getBeansMethod.invoke(beanManager, clazz,
                Array.newInstance(Annotation.class, 0));

        // BeanManager returns no results
        if (beansSet == null || beansSet.size() == 0) {

            if (log.isTraceEnabled()) {
                log.trace("BeanManager doesn't know  class: " + clazz.getName());
            }

            return null;
        }

        // more than one name? Warn the user..
        if (beansSet.size() > 1) {
            log.warn("The BeanManager returns more than one name for " + clazz.getName()
                    + ". You should place a @URLBeanName annotation on the class.");
            return null;
        }

        // get the bean
        Object bean = beansSet.iterator().next();

        // get name from bean instance
        String name = (String) getNameMethod.invoke(bean);

        // log the resolved name
        if (log.isTraceEnabled()) {
            log.trace("BeanManager returned name " + name + " for class: " + clazz.getName());
        }

        return name;

    } catch (IllegalAccessException e) {
        // security issues
        log.warn("Unable to access BeanManager due to security restrictions", e);
    } catch (InvocationTargetException e) {
        // One of the methods we called has thrown an exception
        log.error("Failed to query BeanManager for the bean name...", e);
    }

    return null;
}

From source file:org.brushingbits.jnap.common.bean.cloning.BeanCloner.java

private Object[] cloneArray(Object[] array, Class<?> type) {
    Object[] arrayCopy = (Object[]) Array.newInstance(type, array.length);
    for (int i = 0; i < array.length; i++) {
        arrayCopy[i] = clone(array[i]);//w  w  w .  j  a v  a  2 s . co  m
    }
    return arrayCopy;
}