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:org.crazydog.util.spring.ClassUtils.java

/**
 * Check if the given class represents an array of primitive wrappers,
 * i.e. Boolean, Byte, Character, Short, Integer, Long, Float, or Double.
 * @param clazz the class to check//  w  w  w.j  a  va2s.  c o m
 * @return whether the given class is a primitive wrapper array class
 */
public static boolean isPrimitiveWrapperArray(Class<?> clazz) {
    org.springframework.util.Assert.notNull(clazz, "Class must not be null");
    return (clazz.isArray() && isPrimitiveWrapper(clazz.getComponentType()));
}

From source file:edu.usc.irds.sparkler.solr.schema.FieldMapper.java

/**
 * Maps field name to a dynamic field name based on value content type
 * The map function takes (input field name, value type,  configs, overrides) into consideration
 * for deciding field names//from  w  ww  . j a va 2s  .c  om
 * @param fieldName name of field.
 * @param value value
 * @return mapped solr field name. returns {@code null} when mapping fails
 * @throws IllegalStateException when {@code this.failOnError} is set and an error occurs
 */
public String mapField(String fieldName, Object value) {
    if (overrides.containsKey(fieldName)) {
        return overrides.get(fieldName);
    }
    if (value == null) {
        return null; // null cant be mapped
    }
    Class<?> valType = value.getClass();

    boolean multiValued = false;
    if (valType.isArray()) {
        multiValued = true;
        valType = valType.getComponentType();
        //it could be primitive type, so mapping to Boxed Type
        valType = PRIMITIVE_MAP.getOrDefault(valType, valType);
    } else if (Collection.class.isAssignableFrom(valType)) {
        multiValued = true;
        Collection items = (Collection) value;
        if (items.isEmpty()) {
            return null;
            //cant determine an empty collection
        }
        valType = items.iterator().next().getClass();
    }
    String suffix = typeSuffix.get(valType);
    if (suffix == null) {
        LOG.warn("{} type is not mapped, field name = {}", valType.getName(), fieldName);
        throw new IllegalStateException(valType + " type is not known");
    }

    if (multiValued) {
        suffix += multiValSuffix;
    }
    //is it already mapped
    if (fieldName.endsWith(suffix)) {
        return fieldName;
    }
    fieldName = fieldName.toLowerCase().replaceAll("\\s+", "");
    return fieldName + suffix;
}

From source file:org.blocks4j.reconf.client.config.update.ConfigurationUpdater.java

protected boolean updateMap(String value, boolean newValue, ConfigurationSource obtained,
        ConfigurationItemUpdateResult.Source source) throws Throwable {
    Class<?> clazz = methodCfg.getMethod().getReturnType();
    MethodData data;// ww  w .j  a  v  a2  s  . c o m
    if (clazz.isArray()) {
        data = new MethodData(methodCfg.getMethod(), clazz.getComponentType(), value, obtained.getAdapter());

    } else if (Collection.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz)) {
        data = new MethodData(methodCfg.getMethod(), methodCfg.getMethod().getGenericReturnType(), value,
                obtained.getAdapter());

    } else {
        data = new MethodData(methodCfg.getMethod(), clazz, value, obtained.getAdapter());
    }

    ConfigurationItemElement elem = methodCfg.getConfigurationItemElement();
    ConfigurationItemUpdateResult.Builder builder;

    try {
        if (newValue || isSync) {
            builder = ConfigurationItemUpdateResult.Builder.update(data.getAdapter().adapt(data));

        } else {
            builder = ConfigurationItemUpdateResult.Builder.noChange();
        }

        builder.valueRead(data.getValue()).product(elem.getProduct()).component(elem.getComponent())
                .item(elem.getValue()).method(methodCfg.getMethod()).cast(methodCfg.getMethod().getReturnType())
                .from(source);

    } catch (Throwable t) {
        updateLastResultWithError(source, elem, value, t);
        return false;
    }

    lastResult = builder.build();
    methodValue.put(methodCfg.getMethod(), lastResult);
    return true;
}

From source file:com.glaf.core.util.GetterUtils.java

public static long[] getLongValues(Object value, long[] defaultValue) {
    if (value == null) {
        return defaultValue;
    }//from  www. ja va2 s .  c o  m

    Class<?> clazz = value.getClass();

    if (!clazz.isArray()) {
        return defaultValue;
    }

    Class<?> componentType = clazz.getComponentType();

    if (String.class.isAssignableFrom(componentType)) {
        return getLongValues((String[]) value, defaultValue);
    } else if (Long.class.isAssignableFrom(componentType)) {
        return (long[]) value;
    } else if (Number.class.isAssignableFrom(componentType)) {
        Number[] numbers = (Number[]) value;

        long[] values = new long[numbers.length];

        for (int i = 0; i < values.length; i++) {
            values[i] = numbers[i].longValue();
        }

        return values;
    }

    return defaultValue;
}

From source file:org.apache.servicecomb.swagger.invocation.converter.ConverterMgr.java

protected Converter findCollectionToArray(Type src, Type target) {
    if (ParameterizedType.class.isAssignableFrom(src.getClass()) && target.getClass().equals(Class.class)) {
        ParameterizedType srcType = (ParameterizedType) src;
        Class<?> srcCls = (Class<?>) srcType.getRawType();
        Class<?> targetCls = (Class<?>) target;

        if (Collection.class.isAssignableFrom(srcCls) && targetCls.isArray()
                && srcType.getActualTypeArguments()[0].equals(targetCls.getComponentType())) {
            Converter converter = collectionToArrayMap.computeIfAbsent(target,
                    k -> new SameElementCollectionToArray(targetCls.getComponentType()));
            return converter;
        }/*from   ww  w .  java  2 s.c o  m*/
    }

    return null;
}

From source file:FormatTest.java

/**
 * Adds a row to the main panel.//w w w.  j  a va2 s  .c om
 * @param labelText the label of the field
 * @param field the sample field
 */
public void addRow(String labelText, final JFormattedTextField field) {
    mainPanel.add(new JLabel(labelText));
    mainPanel.add(field);
    final JLabel valueLabel = new JLabel();
    mainPanel.add(valueLabel);
    okButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            Object value = field.getValue();
            Class<?> cl = value.getClass();
            String text = null;
            if (cl.isArray()) {
                if (cl.getComponentType().isPrimitive()) {
                    try {
                        text = Arrays.class.getMethod("toString", cl).invoke(null, value).toString();
                    } catch (Exception ex) {
                        // ignore reflection exceptions
                    }
                } else
                    text = Arrays.toString((Object[]) value);
            } else
                text = value.toString();
            valueLabel.setText(text);
        }
    });
}

From source file:io.servicecomb.swagger.invocation.converter.ConverterMgr.java

protected Converter findCollectionToArray(Type src, Type target) {
    if (ParameterizedType.class.isAssignableFrom(src.getClass()) && target.getClass().equals(Class.class)) {
        ParameterizedType srcType = (ParameterizedType) src;
        Class<?> srcCls = (Class<?>) srcType.getRawType();
        Class<?> targetCls = (Class<?>) target;

        if (Collection.class.isAssignableFrom(srcCls) && targetCls.isArray()
                && srcType.getActualTypeArguments()[0].equals(targetCls.getComponentType())) {
            Converter converter = collectionToArrayMap.get(target);
            if (converter == null) {
                converter = new SameElementCollectionToArray(targetCls.getComponentType());
                collectionToArrayMap.put(target, converter);
            }/* w  w  w  .  j  av  a2 s .  c om*/
            return converter;
        }
    }

    return null;
}

From source file:com.opensymphony.able.introspect.PropertyInfo.java

/**
 * Returns the component type of the property - e.g. ignoring the
 * cardinality (array or List).//from w  w  w .j a va  2 s  . c  o  m
 */
public Class getPropertyComponentType() {
    Class<?> propertyType = descriptor.getPropertyType();

    if (propertyType.isArray()) {
        return propertyType.getComponentType();
    }
    if (Collection.class.isAssignableFrom(propertyType)) {
        if (descriptor.getReadMethod() != null) {
            ParameterizedType genericSuperclass = (ParameterizedType) descriptor.getReadMethod()
                    .getGenericReturnType();
            Type[] typeArguments = genericSuperclass.getActualTypeArguments();
            return (Class) typeArguments[0];
        } else {
            // no idea what the type is
            // TODO do we have an annotation?
            return Object.class;
        }
    }
    return propertyType;
}

From source file:com.qpark.eip.core.spring.JAXBElementAwarePayloadTypeRouter.java

/**
 * Selects the most appropriate channel name matching channel identifiers
 * which are the fully qualified class names encountered while traversing
 * the payload type hierarchy. To resolve ties and conflicts (e.g.,
 * Serializable and String) it will match: 1. Type name to channel
 * identifier else... 2. Name of the subclass of the type to channel
 * identifier else... 3. Name of the Interface of the type to channel
 * identifier while also preferring direct interface over indirect subclass
 *//*from w w w .j  a va2s. c o  m*/
@Override
protected List<Object> getChannelKeys(final Message<?> message) {
    if (CollectionUtils.isEmpty(this.getChannelMappings())) {
        return null;
    }
    Object o = message.getPayload();
    Class<?> type = message.getPayload().getClass();
    if (o.getClass().equals(JAXBElement.class)) {
        type = ((JAXBElement<?>) o).getDeclaredType();
    }
    boolean isArray = type.isArray();
    if (isArray) {
        type = type.getComponentType();
    }
    String closestMatch = this.findClosestMatch(type, isArray);
    return (closestMatch != null) ? Collections.<Object>singletonList(closestMatch) : null;
}

From source file:org.assertj.assertions.generator.description.converter.ClassToClassDescriptionConverter.java

private TypeDescription buildIterableTypeDescription(Member member, final Class<?> type) {
    final TypeDescription typeDescription = new TypeDescription(new TypeName(type));
    typeDescription.setIterable(true);/* www  .  j av a  2 s.co m*/
    if (methodReturnTypeHasNoParameterInfo(member)) {
        // not a ParameterizedType, i.e. no parameter information => use Object as element type.
        typeDescription.setElementTypeName(new TypeName(Object.class));
        return typeDescription;
    }
    ParameterizedType parameterizedType = getParameterizedTypeOf(member);
    if (parameterizedType.getActualTypeArguments()[0] instanceof GenericArrayType) {
        GenericArrayType genericArrayType = (GenericArrayType) parameterizedType.getActualTypeArguments()[0];
        typeDescription.setElementTypeName(new TypeName(genericArrayType.toString()));
        return typeDescription;
    }
    // Due to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7151486,
    // java 7 is not able to detect GenericArrayType correctly => let's use a different way to detect array
    Class<?> internalClass = ClassUtil.getClass(parameterizedType.getActualTypeArguments()[0]);
    if (internalClass.isArray()) {
        String componentTypeWithoutClassPrefix = remove(internalClass.getComponentType().toString(), "class ");
        typeDescription.setElementTypeName(new TypeName(componentTypeWithoutClassPrefix + "[]"));
    } else {
        typeDescription.setElementTypeName(new TypeName(internalClass));
    }
    return typeDescription;
}