Example usage for java.lang Class isArray

List of usage examples for java.lang Class isArray

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native boolean isArray();

Source Link

Document

Determines if this Class object represents an array class.

Usage

From source file:com.britesnow.snow.web.RequestContext.java

/**
 * Return the param value as "cls" class object. If the value is null (or empty string) return the defaultValue.<br>
 * /*ww w.j  av  a 2  s.  c o  m*/
 * Note: For the first call, this method will parse the request (in case of a multipart).<br />
 * 
 * <div class="issues"> <strong>Issues</strong>
 * <ul>
 * <li>FIXME: Need to fix the multipart handling. Can be simplified</li>
 * </ul>
 * </div>
 * 
 * @param <T>
 *            Class of the return element
 * @param name
 *            of the parameter
 * @param cls
 *            Class of the return element
 * @param defaultValue
 *            Default value in case of an error or null/empty value
 * @return
 */
@SuppressWarnings("unchecked")
public <T> T getParamAs(String name, Class<T> cls, T defaultValue) {
    Map<String, Object> paramMap = getParamMap();
    if (paramMap == null) {
        return defaultValue;
    }
    // if we have a primitive type or array, then, just get the single value and convert it to the appropriate type
    if (ObjectUtil.isPrimitive(cls) || cls.isArray() || cls == FileItem.class || cls.isEnum()) {
        // first, try to get it from the paramMap
        Object valueObject = paramMap.get(name);

        if (isMultipart) {
            // HACK
            // if not found, try to get it from the regular HttpServletRequest
            // (in the case of a multiPart post,
            // HttpServletRequest.getParameter still have the URL params)
            if (valueObject == null) {
                valueObject = getReq().getParameter(name);
            }
        }

        if (valueObject == null) {
            return defaultValue;
        } else if (valueObject instanceof String) {
            return (T) ObjectUtil.getValue((String) valueObject, cls, defaultValue);
        } else if (valueObject instanceof String[]) {
            return (T) ObjectUtil.getValue((String[]) valueObject, cls, defaultValue);
        } else {
            // hope for the best (should be a fileItem)
            return (T) valueObject;
        }
    }
    // otherwise, if it is not a primitive type, attempt to create the targeted object with the corresponding
    // paramMap
    else {
        Map subParamMap = getParamMap(name + "."); // i.e., "product."
        if (subParamMap != null) {
            try {
                T value = cls.newInstance();
                ObjectUtil.populate(value, subParamMap);
                return value;
            } catch (Exception e) {
                logger.warn(e.getMessage());
                return defaultValue;
            }
        } else {
            return defaultValue;
        }

    }
}

From source file:com.feilong.commons.core.lang.ClassUtil.java

/**
 *  class info map for log.// w w w .  ja v  a  2s  .c o m
 *
 * @param klass
 *            the clz
 * @return the map for log
 */
public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) {

    Map<String, Object> map = new LinkedHashMap<String, Object>();

    //"clz.getCanonicalName()": "com.feilong.commons.core.date.DatePattern",
    //"clz.getName()": "com.feilong.commons.core.date.DatePattern",
    //"clz.getSimpleName()": "DatePattern",

    // getCanonicalName ( Java Language Specification ??) && getName
    //??class?array?
    // getName[[Ljava.lang.String?getCanonicalName?
    map.put("clz.getCanonicalName()", klass.getCanonicalName());
    map.put("clz.getName()", klass.getName());
    map.put("clz.getSimpleName()", klass.getSimpleName());

    map.put("clz.getComponentType()", klass.getComponentType());
    // ?? voidboolean?byte?char?short?int?long?float  double?
    map.put("clz.isPrimitive()", klass.isPrimitive());

    // ??,
    map.put("clz.isLocalClass()", klass.isLocalClass());
    // ????,??????
    map.put("clz.isMemberClass()", klass.isMemberClass());

    //isSynthetic()?Class????java??false?trueJVM???java??????
    map.put("clz.isSynthetic()", klass.isSynthetic());
    map.put("clz.isArray()", klass.isArray());
    map.put("clz.isAnnotation()", klass.isAnnotation());

    //??true
    map.put("clz.isAnonymousClass()", klass.isAnonymousClass());
    map.put("clz.isEnum()", klass.isEnum());

    return map;
    //      Class<?> klass = this.getClass();
    //
    //      TypeVariable<?>[] typeParameters = klass.getTypeParameters();
    //      TypeVariable<?> typeVariable = typeParameters[0];
    //
    //      Type[] bounds = typeVariable.getBounds();
    //
    //      Type bound = bounds[0];
    //
    //      if (log.isDebugEnabled()){
    //         log.debug("" + (bound instanceof ParameterizedType));
    //      }
    //
    //      Class<T> modelClass = ReflectUtil.getGenericModelClass(klass);
    //      return modelClass;
}

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

public Object clone(Object source) {
    Object copy = null;/*from  w w  w .  j  a  v a2  s .co m*/
    if (source != null) {
        final String currentPath = getCurrentPath();
        final Class<?> type = this.propertyTypeResolver.resolve(source, this.propertyFilter);

        final boolean excluded = type == null || shouldExcludeProperty(currentPath) || shouldExcludeType(type)
                || shouldExcludeAssignableType(type);

        final int currentLevel = context.getCurrentLevel();
        final boolean included = currentLevel == -1 || shouldIncludeProperty(currentPath);
        final boolean validDepth = isValidDepth();

        if (included || (!excluded && validDepth)) {
            if (isStandardType(type)) {
                copy = source;
            } else if (type.isArray()) {
                copy = cloneArray((Object[]) source, type);
            } else if (Collection.class.isAssignableFrom(type)) {
                copy = cloneCollection((Collection<?>) source, type);
            } else if (Map.class.isAssignableFrom(type)) {
                copy = cloneMap((Map<?, ?>) source, type);
            } else {
                // so, we assume it's a nested bean (let's go 'down' another level)
                if (context.wasAlreadyVisited(source) && this.preventCircularVisiting) {
                    copy = null;
                } else if (context.wasAlreadyVisited(source) && !this.preventCircularVisiting) {
                    copy = this.alreadyCloned.get(source);
                } else {
                    context.nextLevel();
                    if (isValidDepth()) {
                        copy = cloneBean(source, type);
                    }
                    context.prevLevel();
                }
            }
        }
    }
    return copy;
}

From source file:java2typescript.jackson.module.StaticFieldExporter.java

private Value constructValue(Module module, Class<?> type, Object rawValue)
        throws IllegalArgumentException, IllegalAccessException {
    if (type == boolean.class) {
        return new Value(BooleanType.getInstance(), rawValue);
    } else if (type == int.class) {
        return new Value(NumberType.getInstance(), rawValue);
    } else if (type == double.class) {
        return new Value(NumberType.getInstance(), rawValue);
    } else if (type == String.class) {
        return new Value(StringType.getInstance(), "'" + (String) rawValue + "'");
    } else if (type.isEnum()) {
        final EnumType enumType = tsJsonFormatVisitorWrapper.parseEnumOrGetFromCache(module,
                SimpleType.construct(type));
        return new Value(enumType, enumType.getName() + "." + rawValue);
    } else if (type.isArray()) {
        final Class<?> componentType = type.getComponentType();
        final Object[] array;
        if (componentType == boolean.class) {
            boolean[] tmpArray = (boolean[]) rawValue;
            array = new Boolean[tmpArray.length];
            for (int i = 0; i < array.length; i++) {
                array[i] = Boolean.valueOf(tmpArray[i]);
            }/*from  w  w w.jav a 2  s  .  c  om*/
        } else if (componentType == int.class) {
            int[] tmpArray = (int[]) rawValue;
            array = new Integer[tmpArray.length];
            for (int i = 0; i < array.length; i++) {
                array[i] = Integer.valueOf(tmpArray[i]);
            }
        } else if (componentType == double.class) {
            double[] tmpArray = (double[]) rawValue;
            array = new Double[tmpArray.length];
            for (int i = 0; i < array.length; i++) {
                array[i] = Double.valueOf(tmpArray[i]);
            }
        } else {
            array = (Object[]) rawValue;
        }
        final StringBuilder arrayValues = new StringBuilder();
        arrayValues.append("[ ");
        for (int i = 0; i < array.length; i++) {
            arrayValues.append(constructValue(module, componentType, array[i]).getValue());
            if (i < array.length - 1) {
                arrayValues.append(", ");
            }
        }
        arrayValues.append(" ]");
        return new Value(new ArrayType(typeScriptTypeFromJavaType(module, componentType)),
                arrayValues.toString());
    }
    return null;
}

From source file:com.github.dozermapper.core.util.ReflectionUtils.java

public static DeepHierarchyElement[] getDeepFieldHierarchy(Class<?> parentClass, String field,
        HintContainer deepIndexHintContainer) {
    if (!MappingUtils.isDeepMapping(field)) {
        MappingUtils.throwMappingException("Field does not contain deep field delimitor");
    }//from  w ww. jav  a 2 s .co  m

    StringTokenizer toks = new StringTokenizer(field, DozerConstants.DEEP_FIELD_DELIMITER);
    Class<?> latestClass = parentClass;
    DeepHierarchyElement[] hierarchy = new DeepHierarchyElement[toks.countTokens()];
    int index = 0;
    int hintIndex = 0;
    while (toks.hasMoreTokens()) {
        String aFieldName = toks.nextToken();
        String theFieldName = aFieldName;
        int collectionIndex = -1;

        if (aFieldName.contains("[")) {
            theFieldName = aFieldName.substring(0, aFieldName.indexOf("["));
            collectionIndex = Integer
                    .parseInt(aFieldName.substring(aFieldName.indexOf("[") + 1, aFieldName.indexOf("]")));
        }

        PropertyDescriptor propDescriptor = findPropertyDescriptor(latestClass, theFieldName,
                deepIndexHintContainer);
        DeepHierarchyElement r = new DeepHierarchyElement(propDescriptor, collectionIndex);

        if (propDescriptor == null) {
            MappingUtils
                    .throwMappingException("Exception occurred determining deep field hierarchy for Class --> "
                            + parentClass.getName() + ", Field --> " + field
                            + ".  Unable to determine property descriptor for Class --> "
                            + latestClass.getName() + ", Field Name: " + aFieldName);
        }

        latestClass = propDescriptor.getPropertyType();
        if (toks.hasMoreTokens()) {
            if (latestClass.isArray()) {
                latestClass = latestClass.getComponentType();
            } else if (Collection.class.isAssignableFrom(latestClass)) {
                Class<?> genericType = determineGenericsType(parentClass.getClass(), propDescriptor);

                if (genericType == null && deepIndexHintContainer == null) {
                    MappingUtils.throwMappingException(
                            "Hint(s) or Generics not specified.  Hint(s) or Generics must be specified for deep mapping with indexed field(s). "
                                    + "Exception occurred determining deep field hierarchy for Class --> "
                                    + parentClass.getName() + ", Field --> " + field
                                    + ".  Unable to determine property descriptor for Class --> "
                                    + latestClass.getName() + ", Field Name: " + aFieldName);
                }

                if (genericType != null) {
                    latestClass = genericType;
                } else {
                    latestClass = deepIndexHintContainer.getHint(hintIndex);
                    hintIndex += 1;
                }
            }
        }
        hierarchy[index++] = r;
    }

    return hierarchy;
}

From source file:fr.mby.utils.spring.beans.factory.support.BasicProxywiredFactory.java

@Override
@SuppressWarnings("unchecked")
public IManageableProxywired proxy(final DependencyDescriptor descriptor,
        final IProxywiredIdentifier identifier, final Object target) {
    Assert.notNull(descriptor, "No DependencyDescriptor provided !");
    Assert.notNull(descriptor, "No IProxywiredIdentifier provided !");
    Assert.notNull(descriptor, "No Target to proxy provided !");

    final IManageableProxywired result;

    final Class<?> dependencyType = descriptor.getDependencyType();

    if (Map.class.isAssignableFrom(dependencyType) && dependencyType.isInterface()) {
        result = this.proxyDependencyMap(identifier, (Map<String, Object>) target);

    } else if (List.class.isAssignableFrom(dependencyType) && dependencyType.isInterface()) {
        result = this.proxyDependencyList(identifier, (List<Object>) target);

    } else if (Collection.class.isAssignableFrom(dependencyType) && dependencyType.isInterface()) {
        result = this.proxyDependencyCollection(identifier, (Collection<Object>) target, dependencyType);

    } else if (dependencyType.isArray()) {
        // We can't do anything
        throw new IllegalStateException("You cannot use Proxywired annotation on an Array !");

    } else if (dependencyType.isInterface()) {

        result = this.proxySingleDependency(identifier, target, dependencyType);
    } else {//  ww w  .  j  ava2 s . com

        throw new IllegalStateException("Dependency type not supported by this factory !");
    }

    return result;
}

From source file:com.spidertracks.datanucleus.convert.ByteConverterContext.java

/**
 * Determine the converter that should be used for this class. Will not
 * perform any caching on converters that are created, however it does check
 * the cache for existing definitions Creates converters with the following
 * order/* www. j av a  2 s . c o m*/
 * 
 * <ol>
 * <li>ByteConverter from converter Mapping</li>
 * <li>ByteAware implementation</li>
 * <li>ObjectLongConverter which is cached</li>
 * <li>ObjectStringConverter which is cached</li>
 * <li>Serialization using the serializer which is cached</li>
 * </ol>
 * 
 * @param clazz
 * @return
 */
private ByteConverter determineConverter(Class<?> clazz) {

    // 1. If there is a converter for the specific class then use it.
    ByteConverter converter = converters.get(clazz);

    if (converter != null) {
        return converter;
    }

    // 2. If the class is an array then look inside of it and try using the inner class.
    if (clazz.isArray()) {
        final ByteConverter innerConverter = this.determineConverter(clazz.getComponentType());
        // It makes no sense to store an array of opaque objects so if the converter
        // is the serializerConverter then we won't bother looking in the array.
        if (innerConverter == this.serializerConverter) {
            return this.serializerConverter;
        }
        return new ArrayConverter(innerConverter, clazz.getComponentType());
    }

    if (ByteAware.class.isAssignableFrom(clazz)) {
        return new ByteAwareConverter(clazz);
    }

    ObjectLongConverter dnLongConverter = typeManager.getLongConverter(clazz);

    if (dnLongConverter != null) {
        return new ObjectLongWrapperConverter(dnLongConverter, this.longConverter);
    }

    ObjectStringConverter dnStringConverter = typeManager.getStringConverter(clazz);

    if (dnStringConverter != null) {
        return new ObjectStringWrapperConverter(dnStringConverter, this.stringConverter);
    }

    return serializerConverter;

}

From source file:javadz.beanutils.locale.LocaleBeanUtilsBean.java

/**
 *  Convert the specified value to the required type.
 *
 * @param type The Java type of target property
 * @param index The indexed subscript value (if any)
 * @param value The value to be converted
 * @return The converted value//from  w  ww.  ja  va  2s  .  c  o m
 */
protected Object convert(Class type, int index, Object value) {

    Object newValue = null;

    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value instanceof String) {
            String[] values = new String[1];
            values[0] = (String) value;
            newValue = ConvertUtils.convert(values, type);
        } else if (value instanceof String[]) {
            newValue = ConvertUtils.convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = ConvertUtils.convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = ConvertUtils.convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if (value instanceof String) {
            newValue = ConvertUtils.convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = ConvertUtils.convert(((String[]) value)[0], type);
        } else {
            newValue = value;
        }
    }
    return newValue;
}

From source file:javadz.beanutils.LazyDynaBean.java

/**
 * Create a new Instance of a Property//  w  w  w  .  j ava2 s.  c om
 * @param name The name of the property
 * @param type The class of the property
 * @return The new value
 */
protected Object createProperty(String name, Class type) {
    if (type == null) {
        return null;
    }

    // Create Lists, arrays or DynaBeans
    if (type.isArray() || List.class.isAssignableFrom(type)) {
        return createIndexedProperty(name, type);
    }

    if (Map.class.isAssignableFrom(type)) {
        return createMappedProperty(name, type);
    }

    if (DynaBean.class.isAssignableFrom(type)) {
        return createDynaBeanProperty(name, type);
    }

    if (type.isPrimitive()) {
        return createPrimitiveProperty(name, type);
    }

    if (Number.class.isAssignableFrom(type)) {
        return createNumberProperty(name, type);
    }

    return createOtherProperty(name, type);

}

From source file:org.boris.xlloop.util.XLoperObjectConverter.java

/**
 * Creates a java object from an XLObject.
 * //from  www  .  j  ava 2s  .c  o  m
 * @param obj.
 * @param hint.
 * 
 * @return Object.
 */
public Object createFrom(XLoper obj, Class hint, SessionContext sessionContext) {
    // If Excel passes a single value and the Java code expects an array,
    // try to convert based on the component type, and then create the
    // array.
    if (obj.type != XLoper.xlTypeMulti && hint.isArray()) {
        Object value = doTypeSwitch(obj, hint.getComponentType(), sessionContext);
        Object array = Array.newInstance(hint.getComponentType(), 1);
        Array.set(array, 0, value);
        return array;
    } else {
        return doTypeSwitch(obj, hint, sessionContext);
    }
}