Example usage for java.lang Class getComponentType

List of usage examples for java.lang Class getComponentType

Introduction

In this page you can find the example usage for java.lang Class getComponentType.

Prototype

public Class<?> getComponentType() 

Source Link

Document

Returns the Class representing the component type of an array.

Usage

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);
    }/*from  w  w  w.  ja  v a 2s.c o m*/
    return sourceWrapper;
}

From source file:CopyOnWriteArrayList.java

private static Object[] copyOfRange(Object[] original, int from, int to, Class newType) {
    int newLength = to - from;
    if (newLength < 0)
        throw new IllegalArgumentException(from + " > " + to);
    Object[] copy = (Object[]) java.lang.reflect.Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength));
    return copy;/*from ww w.  j a  va2s  . c o  m*/
}

From source file:org.apache.axis2.transport.testkit.tests.TestResource.java

public void resolve(TestResourceSet resourceSet) {
    if (status != Status.UNRESOLVED) {
        return;/*www  .  j a v a2 s.c om*/
    }
    for (Class<?> clazz = target.getClass(); !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getAnnotation(Setup.class) != null) {
                Type[] parameterTypes = method.getGenericParameterTypes();
                Object[] args = new Object[parameterTypes.length];
                for (int i = 0; i < parameterTypes.length; i++) {
                    Type parameterType = parameterTypes[i];
                    if (!(parameterType instanceof Class)) {
                        throw new Error("Generic parameters not supported in " + method);
                    }
                    Class<?> parameterClass = (Class<?>) parameterType;
                    if (parameterClass.isArray()) {
                        Class<?> componentType = parameterClass.getComponentType();
                        TestResource[] resources = resourceSet.findResources(componentType, true);
                        Object[] arg = (Object[]) Array.newInstance(componentType, resources.length);
                        for (int j = 0; j < resources.length; j++) {
                            TestResource resource = resources[j];
                            directDependencies.add(resource);
                            arg[j] = resource.getInstance();
                        }
                        args[i] = arg;
                    } else {
                        TestResource[] resources = resourceSet.findResources(parameterClass, true);
                        if (resources.length == 0) {
                            throw new Error(target.getClass().getName() + " depends on "
                                    + parameterClass.getName() + ", but none found");
                        } else if (resources.length > 1) {
                            throw new Error(target.getClass().getName() + " depends on "
                                    + parameterClass.getName() + ", but multiple candidates found");

                        }
                        TestResource resource = resources[0];
                        directDependencies.add(resource);
                        args[i] = resource.getInstance();
                    }
                }
                method.setAccessible(true);
                initializers.addFirst(new MethodInvocation(method, args));
            } else if (method.getAnnotation(TearDown.class) != null && method.getParameterTypes().length == 0) {
                method.setAccessible(true);
                finalizers.add(new MethodInvocation(method, null));
            }
        }
        for (Field field : clazz.getDeclaredFields()) {
            if (field.getAnnotation(Transient.class) != null) {
                field.setAccessible(true);
                finalizers.add(new FieldResetter(field));
            }
        }
    }
    status = Status.RESOLVED;
}

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * @param clazz/*from   w ww. j  av a 2s.c om*/
 *            the class
 * @param runtime
 *            flag <code>true</code> if we need name for class loading, <code>false</code> if we need name
 *            for source generation.
 * 
 * @return the fully qualified name of given {@link Class}
 */
public static String getFullyQualifiedName(Class<?> clazz, boolean runtime) {
    Assert.isNotNull(clazz);
    if (runtime) {
        // primitive
        if (clazz.isPrimitive()) {
            if (clazz == void.class) {
                return "V";
            } else if (clazz == boolean.class) {
                return "Z";
            } else if (clazz == byte.class) {
                return "B";
            } else if (clazz == char.class) {
                return "C";
            } else if (clazz == short.class) {
                return "S";
            } else if (clazz == int.class) {
                return "I";
            } else if (clazz == long.class) {
                return "J";
            } else if (clazz == float.class) {
                return "F";
            } else if (clazz == double.class) {
                return "D";
            }
        }
        // array
        if (clazz.isArray()) {
            return "[" + getFullyQualifiedName(clazz.getComponentType(), runtime);
        }
        // object
        return "L" + clazz.getName() + ";";
    } else {
        // primitive
        if (clazz.isPrimitive()) {
            return clazz.getName();
        }
        // array
        if (clazz.isArray()) {
            return getFullyQualifiedName(clazz.getComponentType(), runtime) + "[]";
        }
        // object
        return clazz.getName().replace('/', '.').replace('$', '.');
    }
}

From source file:com.wantscart.jade.provider.jdbc.PreparedStatementCallbackReturnId.java

public PreparedStatementCallbackReturnId(PreparedStatementSetter setter, Class<?> returnType) {
    this.setter = setter;
    if (returnType.isPrimitive()) {
        returnType = ClassUtils.primitiveToWrapper(returnType);
    }//  w w w .ja v a2s  . c om
    this.returnType = returnType;
    Class<?> idType = returnType;
    if (returnType.isArray()) {
        idType = returnType.getComponentType();
    }
    this.idType = idType;
    if (idType.isPrimitive()) {
        idType = ClassUtils.primitiveToWrapper(idType);
    }
    this.wrappedIdType = idType;
    this.mapper = new SingleColumnRowMapper(idType);
    if (wrappedIdType != Integer.class && wrappedIdType != Long.class && wrappedIdType != Number.class) {
        throw new IllegalArgumentException(
                "wrong return type(int/long type or its array type only): " + returnType);
    }
}

From source file:br.gov.frameworkdemoiselle.internal.configuration.ConfigurationLoader.java

/**
 * Returns the value associated with the given configuration class and field type.
 * /*from   w  w w .j a  v  a 2 s.com*/
 * @param name
 * @param config
 * @param fieldClass
 * @return the value
 */
@SuppressWarnings("unchecked")
private <T> T getValue(String key, Class<T> fieldClass, org.apache.commons.configuration.Configuration config) {
    Object value;

    if (fieldClass.isArray() && fieldClass.getComponentType().equals(String.class)) {
        value = config.getStringArray(key);

    } else if (fieldClass.equals(Properties.class)) {
        value = getProperty(key, config);

    } else {
        value = getBasic(key, fieldClass, config);
    }

    return (T) value;
}

From source file:org.brekka.phalanx.core.services.impl.AbstractCryptoService.java

@SuppressWarnings("unchecked")
protected <T> T toType(byte[] data, Class<T> expectedType, UUID idOfData, CryptoProfile cryptoProfile) {
    if (expectedType == null) {
        throw new NullPointerException("An expected type is required");
    }//from   w  w w  .  j a  va2s  .  c o m
    Object retVal;
    if (expectedType.isArray() && expectedType.getComponentType() == Byte.TYPE) {
        retVal = data;
    } else if (expectedType == InternalPrivateKeyToken.class) {
        retVal = decodePrivateKey(data, idOfData, cryptoProfile);
    } else if (expectedType == InternalSecretKeyToken.class) {
        retVal = decodeSecretKey(data, idOfData);
    } else {
        throw new IllegalArgumentException(
                String.format("Unsupport type conversion to '%s'", expectedType.getName()));
    }
    return (T) retVal;
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

private static <T> T pbRecurrence(Class<T> c, String prefix) throws RuntimeException {
    try {//from   ww w  .  j  ava  2 s .com
        HttpServletRequest request = ActionContext.getReq();
        T newInstance = c.newInstance();
        Field[] declaredFields = c.getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            String name = field.getName();
            String key = "".equals(prefix) ? name : prefix + "." + name;
            String value = request.getParameter(key);

            Class<?> type = field.getType();
            if (type.isArray()) {//?string   file
                Class<?> componentType = type.getComponentType();
                if (componentType == String.class) {
                    String[] values = request.getParameterValues(name);
                    //                    if (null == value || "".equals(value)) continue;
                    //                    String[] split = value.split(",");
                    field.set(newInstance, values);
                } else if (componentType == File.class) {
                    ServletContext servletContext = getServletContext();
                    File file = new File(servletContext.getRealPath("upload"));
                    if (!file.exists())
                        file.mkdir();
                    MultipartRequest multi = new MultipartRequest(request, file.getAbsolutePath(),
                            1024 * 1024 * 1024, "UTF-8", new DefaultFileRenamePolicy());
                    Enumeration files = multi.getFileNames();
                    List<File> fileList = new ArrayList<File>();
                    if (files.hasMoreElements()) {
                        File f = multi.getFile((String) files.nextElement());
                        fileList.add(f);
                    }
                    field.set(newInstance, fileList.toArray(new File[] {}));
                }

            }
            // ? 
            validation(field, name, value);
            if (null == value) {
                continue;
            }
            if (type == Long.class) {
                field.set(newInstance, Long.parseLong(value));
            } else if (type == String.class) {
                field.set(newInstance, value);
            } else if (type == Byte.class) {
                field.set(newInstance, Byte.parseByte(value));
            } else if (type == Integer.class) {
                field.set(newInstance, Integer.parseInt(value));
            } else if (type == Character.class) {
                field.set(newInstance, value.charAt(0));
            } else if (type == Boolean.class) {
                field.set(newInstance, Boolean.parseBoolean(value));
            } else if (type == Double.class) {
                field.set(newInstance, Double.parseDouble(value));
            } else if (type == Float.class) {
                field.set(newInstance, Float.parseFloat(value));
            } else if (type == Date.class) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                field.set(newInstance, sdf.parse(value));
            } else { // 
                Object obj = pbRecurrence(field.getType(), name);// 
                field.set(newInstance, obj);
            }
        }
        return newInstance;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hzc.framework.ssh.controller.WebUtil.java

/**
 * ?????bean<br/>//from   w  ww.  j  a  va2s .  co  m
 * ???
 *
 * @param <T>
 * @throws ValidationException
 */
public static <T> T packBean(Class<T> c) throws RuntimeException {
    try {
        HttpServletRequest request = ActionContext.getReq();
        T newInstance = c.newInstance();
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String name = field.getName();
            String value = request.getParameter(name);

            Class<?> type = field.getType();
            if (type.isArray()) {//?string   file
                Class<?> componentType = type.getComponentType();
                if (componentType == String.class) {
                    String[] values = request.getParameterValues(name);
                    //                    if (null == value || "".equals(value)) continue;
                    //                    String[] split = value.split(",");
                    field.set(newInstance, values);
                } else if (componentType == File.class) {
                    ServletContext servletContext = getServletContext();
                    File file = new File(servletContext.getRealPath("upload"));
                    if (!file.exists())
                        file.mkdir();
                    MultipartRequest multi = new MultipartRequest(request, file.getAbsolutePath(),
                            MAX_POST_SIZE, "UTF-8", new DefaultFileRenamePolicy());
                    Enumeration files = multi.getFileNames();
                    List<File> fileList = new ArrayList<File>();
                    if (files.hasMoreElements()) {
                        File f = multi.getFile((String) files.nextElement());
                        fileList.add(f);
                    }
                    field.set(newInstance, fileList.toArray(new File[] {}));
                }

            }
            //            else if (type == File.class) {//?
            //                ServletContext servletContext = getServletContext();
            //                File file = new File(servletContext.getRealPath("upload"));
            //                if (!file.exists())
            //                    file.mkdir();
            //                MultipartRequest multi =
            //                        new MultipartRequest(request, file.getAbsolutePath(), 10 * 1024 * 1024, "UTF-8", new DefaultFileRenamePolicy());
            //                Enumeration files = multi.getFileNames();
            //                if (files.hasMoreElements()) {
            //                    field.set(newInstance, multi.getFile((String) files.nextElement()));
            //                }
            //            }
            // ? 
            validation(field, name, value);
            if (null == value || "".equals(value.trim())) {
                continue;
            }
            if (type == Long.class) {
                field.set(newInstance, Long.parseLong(value));
            } else if (type == String.class) {
                field.set(newInstance, value);
            } else if (type == Byte.class) {
                field.set(newInstance, Byte.parseByte(value));
            } else if (type == Integer.class) {
                field.set(newInstance, Integer.parseInt(value));
            } else if (type == Character.class) {
                field.set(newInstance, value.charAt(0));
            } else if (type == Boolean.class) {
                field.set(newInstance, Boolean.parseBoolean(value));
            } else if (type == Double.class) {
                field.set(newInstance, Double.parseDouble(value));
            } else if (type == Float.class) {
                field.set(newInstance, Float.parseFloat(value));
            } else if (type == Date.class) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                field.set(newInstance, sdf.parse(value));
            }
        }
        return newInstance;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.espertech.esper.event.EventTypeUtility.java

public static PropertySetDescriptor getNestableProperties(Map<String, Object> propertiesToAdd,
        EventAdapterService eventAdapterService, EventTypeNestableGetterFactory factory,
        EventType[] optionalSuperTypes) throws EPException {
    List<String> propertyNameList = new ArrayList<String>();
    List<EventPropertyDescriptor> propertyDescriptors = new ArrayList<EventPropertyDescriptor>();
    Map<String, Object> nestableTypes = new LinkedHashMap<String, Object>();
    Map<String, PropertySetDescriptorItem> propertyItems = new HashMap<String, PropertySetDescriptorItem>();

    // handle super-types first, such that the order of properties is well-defined from super-type to subtype
    if (optionalSuperTypes != null) {
        for (int i = 0; i < optionalSuperTypes.length; i++) {
            BaseNestableEventType superType = (BaseNestableEventType) optionalSuperTypes[i];
            for (String propertyName : superType.getPropertyNames()) {
                if (nestableTypes.containsKey(propertyName)) {
                    continue;
                }/*  w  ww  .  j a  va2s  .c  o m*/
                propertyNameList.add(propertyName);
            }
            for (EventPropertyDescriptor descriptor : superType.getPropertyDescriptors()) {
                if (nestableTypes.containsKey(descriptor.getPropertyName())) {
                    continue;
                }
                propertyDescriptors.add(descriptor);
            }

            propertyItems.putAll(superType.propertyItems);
            nestableTypes.putAll(superType.nestableTypes);
        }
    }

    nestableTypes.putAll(propertiesToAdd);

    // Initialize getters and names array: at this time we do not care about nested types,
    // these are handled at the time someone is asking for them
    for (Map.Entry<String, Object> entry : propertiesToAdd.entrySet()) {
        if (!(entry.getKey() instanceof String)) {
            throw new EPException("Invalid type configuration: property name is not a String-type value");
        }
        String name = entry.getKey();

        // handle types that are String values
        if (entry.getValue() instanceof String) {
            String value = entry.getValue().toString().trim();
            Class clazz = JavaClassHelper.getPrimitiveClassForName(value);
            if (clazz != null) {
                entry.setValue(clazz);
            }
        }

        if (entry.getValue() instanceof Class) {
            Class classType = (Class) entry.getValue();

            boolean isArray = classType.isArray();
            Class componentType = null;
            if (isArray) {
                componentType = classType.getComponentType();
            }
            boolean isMapped = JavaClassHelper.isImplementsInterface(classType, Map.class);
            if (isMapped) {
                componentType = Object.class; // Cannot determine the type at runtime
            }
            boolean isFragment = JavaClassHelper.isFragmentableType(classType);
            BeanEventType nativeFragmentType = null;
            FragmentEventType fragmentType = null;
            if (isFragment) {
                fragmentType = EventBeanUtility.createNativeFragmentType(classType, null, eventAdapterService);
                if (fragmentType != null) {
                    nativeFragmentType = (BeanEventType) fragmentType.getFragmentType();
                } else {
                    isFragment = false;
                }
            }
            EventPropertyGetter getter = factory.getGetterProperty(name, nativeFragmentType,
                    eventAdapterService);
            EventPropertyDescriptor descriptor = new EventPropertyDescriptor(name, classType, componentType,
                    false, false, isArray, isMapped, isFragment);
            PropertySetDescriptorItem item = new PropertySetDescriptorItem(descriptor, classType, getter,
                    fragmentType);
            propertyNameList.add(name);
            propertyDescriptors.add(descriptor);
            propertyItems.put(name, item);
            continue;
        }

        // A null-type is also allowed
        if (entry.getValue() == null) {
            EventPropertyGetter getter = factory.getGetterProperty(name, null, null);
            EventPropertyDescriptor descriptor = new EventPropertyDescriptor(name, null, null, false, false,
                    false, false, false);
            PropertySetDescriptorItem item = new PropertySetDescriptorItem(descriptor, null, getter, null);
            propertyNameList.add(name);
            propertyDescriptors.add(descriptor);
            propertyItems.put(name, item);
            continue;
        }

        // Add Map itself as a property
        if (entry.getValue() instanceof Map) {
            EventPropertyGetter getter = factory.getGetterProperty(name, null, null);
            EventPropertyDescriptor descriptor = new EventPropertyDescriptor(name, Map.class, null, false,
                    false, false, true, false);
            PropertySetDescriptorItem item = new PropertySetDescriptorItem(descriptor, Map.class, getter, null);
            propertyNameList.add(name);
            propertyDescriptors.add(descriptor);
            propertyItems.put(name, item);
            continue;
        }

        if (entry.getValue() instanceof EventType) {
            // Add EventType itself as a property
            EventPropertyGetter getter = factory.getGetterEventBean(name);
            EventType eventType = (EventType) entry.getValue();
            EventPropertyDescriptor descriptor = new EventPropertyDescriptor(name,
                    eventType.getUnderlyingType(), null, false, false, false, false, true);
            FragmentEventType fragmentEventType = new FragmentEventType(eventType, false, false);
            PropertySetDescriptorItem item = new PropertySetDescriptorItem(descriptor,
                    eventType.getUnderlyingType(), getter, fragmentEventType);
            propertyNameList.add(name);
            propertyDescriptors.add(descriptor);
            propertyItems.put(name, item);
            continue;
        }

        if (entry.getValue() instanceof EventType[]) {
            // Add EventType array itself as a property, type is expected to be first array element
            EventType eventType = ((EventType[]) entry.getValue())[0];
            Object prototypeArray = Array.newInstance(eventType.getUnderlyingType(), 0);
            EventPropertyGetter getter = factory.getGetterEventBeanArray(name, eventType);
            EventPropertyDescriptor descriptor = new EventPropertyDescriptor(name, prototypeArray.getClass(),
                    eventType.getUnderlyingType(), false, false, true, false, true);
            FragmentEventType fragmentEventType = new FragmentEventType(eventType, true, false);
            PropertySetDescriptorItem item = new PropertySetDescriptorItem(descriptor,
                    prototypeArray.getClass(), getter, fragmentEventType);
            propertyNameList.add(name);
            propertyDescriptors.add(descriptor);
            propertyItems.put(name, item);
            continue;
        }

        if (entry.getValue() instanceof String) {
            String propertyName = entry.getValue().toString();
            boolean isArray = EventTypeUtility.isPropertyArray(propertyName);
            if (isArray) {
                propertyName = EventTypeUtility.getPropertyRemoveArray(propertyName);
            }

            // Add EventType itself as a property
            EventType eventType = eventAdapterService.getExistsTypeByName(propertyName);
            if (!(eventType instanceof BaseNestableEventType)) {
                throw new EPException(
                        "Nestable type configuration encountered an unexpected property type name '"
                                + entry.getValue() + "' for property '" + name
                                + "', expected java.lang.Class or java.util.Map or the name of a previously-declared Map or ObjectArray type");
            }

            Class underlyingType = eventType.getUnderlyingType();
            if (isArray) {
                underlyingType = Array.newInstance(underlyingType, 0).getClass();
            }
            EventPropertyGetter getter;
            if (!isArray) {
                getter = factory.getGetterBeanNested(name, eventType, eventAdapterService);
            } else {
                getter = factory.getGetterBeanNestedArray(name, eventType, eventAdapterService);
            }
            EventPropertyDescriptor descriptor = new EventPropertyDescriptor(name, underlyingType, null, false,
                    false, isArray, false, true);
            FragmentEventType fragmentEventType = new FragmentEventType(eventType, isArray, false);
            PropertySetDescriptorItem item = new PropertySetDescriptorItem(descriptor, underlyingType, getter,
                    fragmentEventType);
            propertyNameList.add(name);
            propertyDescriptors.add(descriptor);
            propertyItems.put(name, item);
            continue;
        }

        generateExceptionNestedProp(name, entry.getValue());
    }

    return new PropertySetDescriptor(propertyNameList, propertyDescriptors, propertyItems, nestableTypes);
}