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.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java

/**
 * Extension point to create the model attribute if not found in the model. The default implementation uses the
 * default constructor./*from w w w.j  a v a 2 s  .c  o m*/
 * 
 * @param attributeName the name of the attribute, never {@code null}
 * @param parameter the method parameter
 * @param binderFactory for creating WebDataBinder instance
 * @param request the current request
 * @return the created model attribute, never {@code null}
 */
protected Object createAttribute(String attributeName, MethodParameter parameter,
        WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {

    String value = getRequestValueForAttribute(attributeName, request);

    if (value != null) {
        Object attribute = createAttributeFromRequestValue(value, attributeName, parameter, binderFactory,
                request);
        if (attribute != null) {
            return attribute;
        }
    }
    Class<?> parameterType = parameter.getParameterType();
    if (parameterType.isArray() || List.class.isAssignableFrom(parameterType)) {
        return ArrayList.class.newInstance();
    }
    if (Set.class.isAssignableFrom(parameterType)) {
        return HashSet.class.newInstance();
    }

    if (MapWapper.class.isAssignableFrom(parameterType)) {
        return MapWapper.class.newInstance();
    }

    return BeanUtils.instantiateClass(parameter.getParameterType());
}

From source file:org.crank.javax.faces.component.MenuRenderer.java

/**
 * Converts the provided string array and places them into the correct provided model type.
 * @param context//from   w w  w.  j a va2 s . c o  m
 * @param uiSelectMany
 * @param modelType
 * @param newValues
 * @return
 */
private Object convertSelectManyValuesForModel(FacesContext context, UISelectMany uiSelectMany,
        Class<?> modelType, String[] newValues) {
    Object result = null;
    if (modelType.isArray()) {
        result = convertSelectManyValues(context, uiSelectMany, modelType, newValues);
    } else if (List.class.isAssignableFrom(modelType)) {
        result = Arrays
                .asList((Object[]) convertSelectManyValues(context, uiSelectMany, Object[].class, newValues));
    }
    return result;
}

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

/**
 * Parses object with follow rules:/*  w  w w  . j a v  a 2s . c  om*/
 *
 * 1. All fields should had a public access.
 * 2. The name of the filed should be fully equal to name of JSONObject key.
 * 3. Supports parse of all Java primitives, all {@link java.lang.String},
 *  arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s,
 *  list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes},
 *  {@link com.vk.sdkweb.api.model.VKApiModel}s.
 *
 * 4. Boolean fields defines by vk_int == 1 expression.
 *
 * @param object object to initialize
 * @param source data to read values
 * @param <T> type of result
 * @return initialized according with given data object
 * @throws JSONException if source object structure is invalid
 */
@SuppressWarnings("rawtypes")
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            //  ?:
            //   ,     getFields()   .
            //  ? ? ?,   ? ?,  Android  ?  .
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:com.liferay.portal.template.soy.internal.SoyTemplate.java

protected Object getSoyMapValue(Object value) {
    if (value == null) {
        return null;
    }/*  w ww. j  ava  2 s .  co  m*/

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

    if (ClassUtils.isPrimitiveOrWrapper(clazz) || value instanceof String) {
        return value;
    }

    if (clazz.isArray()) {
        List<Object> newList = new ArrayList<>();

        for (int i = 0; i < Array.getLength(value); i++) {
            Object object = Array.get(value, i);

            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof Iterable) {
        @SuppressWarnings("unchecked")
        Iterable<Object> iterable = (Iterable<Object>) value;

        List<Object> newList = new ArrayList<>();

        for (Object object : iterable) {
            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) value;

        List<Object> newList = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            Object object = jsonArray.opt(i);

            newList.add(getSoyMapValue(object));
        }

        return newList;
    }

    if (value instanceof Map) {
        Map<Object, Object> map = (Map<Object, Object>) value;

        Map<Object, Object> newMap = new TreeMap<>();

        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Object newKey = getSoyMapValue(entry.getKey());

            if (newKey == null) {
                continue;
            }

            Object newValue = getSoyMapValue(entry.getValue());

            newMap.put(newKey, newValue);
        }

        return newMap;
    }

    if (value instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) value;

        Map<String, Object> newMap = new TreeMap<>();

        Iterator<String> iterator = jsonObject.keys();

        while (iterator.hasNext()) {
            String key = iterator.next();

            Object object = jsonObject.get(key);

            Object newValue = getSoyMapValue(object);

            newMap.put(key, newValue);
        }

        return newMap;
    }

    if (value instanceof org.json.JSONObject) {
        org.json.JSONObject jsonObject = (org.json.JSONObject) value;

        Map<Object, Object> newMap = new TreeMap<>();

        Iterator<String> iterator = jsonObject.keys();

        while (iterator.hasNext()) {
            String key = iterator.next();

            Object object = jsonObject.opt(key);

            Object newValue = getSoyMapValue(object);

            newMap.put(key, newValue);
        }

        return newMap;
    }

    if (value instanceof SoyRawData) {
        SoyRawData soyRawData = (SoyRawData) value;

        return soyRawData.getValue();
    }

    Map<String, Object> newMap = new TreeMap<>();

    BeanPropertiesUtil.copyProperties(value, newMap);

    if (newMap.isEmpty()) {
        return null;
    }

    return getSoyMapValue(newMap);
}

From source file:com.sunchenbin.store.feilong.core.lang.ClassUtil.java

/**
 *  class info map for LOGGER.//from   ww  w  .ja v a  2 s. c  o  m
 *
 * @param klass
 *            the clz
 * @return the map for log
 */
public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) {
    if (Validator.isNullOrEmpty(klass)) {
        return Collections.emptyMap();
    }

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

    map.put("clz.getCanonicalName()", klass.getCanonicalName());//"com.sunchenbin.store.feilong.core.date.DatePattern"
    map.put("clz.getName()", klass.getName());//"com.sunchenbin.store.feilong.core.date.DatePattern"
    map.put("clz.getSimpleName()", klass.getSimpleName());//"DatePattern"

    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,?true,JVM???,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;
}

From source file:es.caib.zkib.jxpath.util.BasicTypeConverter.java

/**
 * Converts the supplied object to the specified
 * type. Throws a runtime exception if the conversion is
 * not possible.//from  w w w.jav  a  2  s.  co  m
 * @param object to convert
 * @param toType destination class
 * @return converted object
 */
public Object convert(Object object, final Class toType) {
    if (object == null) {
        return toType.isPrimitive() ? convertNullToPrimitive(toType) : null;
    }

    if (toType == Object.class) {
        if (object instanceof NodeSet) {
            return convert(((NodeSet) object).getValues(), toType);
        }
        if (object instanceof Pointer) {
            return convert(((Pointer) object).getValue(), toType);
        }
        return object;
    }
    final Class useType = TypeUtils.wrapPrimitive(toType);
    Class fromType = object.getClass();

    if (useType.isAssignableFrom(fromType)) {
        return object;
    }

    if (fromType.isArray()) {
        int length = Array.getLength(object);
        if (useType.isArray()) {
            Class cType = useType.getComponentType();

            Object array = Array.newInstance(cType, length);
            for (int i = 0; i < length; i++) {
                Object value = Array.get(object, i);
                Array.set(array, i, convert(value, cType));
            }
            return array;
        }
        if (Collection.class.isAssignableFrom(useType)) {
            Collection collection = allocateCollection(useType);
            for (int i = 0; i < length; i++) {
                collection.add(Array.get(object, i));
            }
            return unmodifiableCollection(collection);
        }
        if (length > 0) {
            Object value = Array.get(object, 0);
            return convert(value, useType);
        }
        return convert("", useType);
    }
    if (object instanceof Collection) {
        int length = ((Collection) object).size();
        if (useType.isArray()) {
            Class cType = useType.getComponentType();
            Object array = Array.newInstance(cType, length);
            Iterator it = ((Collection) object).iterator();
            for (int i = 0; i < length; i++) {
                Object value = it.next();
                Array.set(array, i, convert(value, cType));
            }
            return array;
        }
        if (Collection.class.isAssignableFrom(useType)) {
            Collection collection = allocateCollection(useType);
            collection.addAll((Collection) object);
            return unmodifiableCollection(collection);
        }
        if (length > 0) {
            Object value;
            if (object instanceof List) {
                value = ((List) object).get(0);
            } else {
                Iterator it = ((Collection) object).iterator();
                value = it.next();
            }
            return convert(value, useType);
        }
        return convert("", useType);
    }
    if (object instanceof NodeSet) {
        return convert(((NodeSet) object).getValues(), useType);
    }
    if (object instanceof Pointer) {
        return convert(((Pointer) object).getValue(), useType);
    }
    if (useType == String.class) {
        return object.toString();
    }
    if (object instanceof Boolean) {
        if (Number.class.isAssignableFrom(useType)) {
            return allocateNumber(useType, ((Boolean) object).booleanValue() ? 1 : 0);
        }
        if ("java.util.concurrent.atomic.AtomicBoolean".equals(useType.getName())) {
            try {
                return useType.getConstructor(new Class[] { boolean.class })
                        .newInstance(new Object[] { object });
            } catch (Exception e) {
                throw new JXPathTypeConversionException(useType.getName(), e);
            }
        }
    }
    if (object instanceof Number) {
        double value = ((Number) object).doubleValue();
        if (useType == Boolean.class) {
            return value == 0.0 ? Boolean.FALSE : Boolean.TRUE;
        }
        if (Number.class.isAssignableFrom(useType)) {
            return allocateNumber(useType, value);
        }
    }
    if (object instanceof String) {
        Object value = convertStringToPrimitive(object, useType);
        if (value != null || "".equals(object)) {
            return value;
        }
    }

    Converter converter = ConvertUtils.lookup(useType);
    if (converter != null) {
        return converter.convert(useType, object);
    }

    throw new JXPathTypeConversionException("Cannot convert " + object.getClass() + " to " + useType);
}

From source file:com.google.ratel.util.RatelUtils.java

private static Object createDeepInstance(Class type, Set<Class> cyclicDetector) {
    cyclicDetector.add(type);/*from   w w w  . j  a  v a  2s .c o m*/
    //System.out.println("Depth: " + callingDepth);

    try {
        Object obj = null;

        // Handle primitives
        if (defaultValues.containsKey(type)) {
            Object defaultValue = defaultValues.get(type);
            obj = defaultValue;

            // Handle Arrays
        } else if (type.isArray()) {
            Class arrayType = type.getComponentType();

            // Check cyclic dependency
            if (!cyclicDetector.contains(arrayType)) {

                Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector);
                Object value = createDeepInstance(arrayType, localCyclicDetector);
                obj = Array.newInstance(arrayType, 1);
                Array.set(obj, 0, value);
            }

        } else {
            // Handle pojo
            obj = type.newInstance();

            List<Field> fullFieldList = getAllFields(type);

            for (Field field : fullFieldList) {
                Class fieldType = field.getType();

                // Check for cyclic dependency
                if (!cyclicDetector.contains(fieldType)) {
                    Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector);
                    Object fieldObj = createDeepInstance(fieldType, localCyclicDetector);
                    if (!Modifier.isPublic(field.getModifiers())) {
                        field.setAccessible(true);
                    }

                    field.set(obj, fieldObj);

                    if (!Modifier.isPublic(field.getModifiers())) {
                        field.setAccessible(false);
                    }
                }

            }
        }
        return obj;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java

/**
 * Converts whatever it gets to a string. But it does it in a sensitive way.
 * E.g. it tries to detect collections and returns the first element (if there is only one). 
 * Never returns null. Returns empty string instead. 
 *//*  w w w  . j av  a  2s .  c  o  m*/
public String stringify(Object whatever) {

    if (whatever == null) {
        return "";
    }

    if (whatever instanceof String) {
        return (String) whatever;
    }

    if (whatever instanceof PolyString) {
        return ((PolyString) whatever).getOrig();
    }

    if (whatever instanceof PolyStringType) {
        return ((PolyStringType) whatever).getOrig();
    }

    if (whatever instanceof Collection) {
        Collection collection = (Collection) whatever;
        if (collection.isEmpty()) {
            return "";
        }
        if (collection.size() > 1) {
            throw new IllegalArgumentException(
                    "Cannot stringify collection because it has " + collection.size() + " values");
        }
        whatever = collection.iterator().next();
    }

    Class<? extends Object> whateverClass = whatever.getClass();
    if (whateverClass.isArray()) {
        Object[] array = (Object[]) whatever;
        if (array.length == 0) {
            return "";
        }
        if (array.length > 1) {
            throw new IllegalArgumentException(
                    "Cannot stringify array because it has " + array.length + " values");
        }
        whatever = array[0];
    }

    if (whatever == null) {
        return "";
    }

    if (whatever instanceof String) {
        return (String) whatever;
    }

    if (whatever instanceof PolyString) {
        return ((PolyString) whatever).getOrig();
    }

    if (whatever instanceof PolyStringType) {
        return ((PolyStringType) whatever).getOrig();
    }

    if (whatever instanceof Element) {
        Element element = (Element) whatever;
        Element origElement = DOMUtil.getChildElement(element, PolyString.F_ORIG);
        if (origElement != null) {
            // This is most likely a PolyStringType
            return origElement.getTextContent();
        } else {
            return element.getTextContent();
        }
    }

    if (whatever instanceof Node) {
        return ((Node) whatever).getTextContent();
    }

    return whatever.toString();
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Checks if is array./*  w  ww  . ja v  a2s. c o m*/
 * 
 * @param clazz
 *          the clazz
 * @return the boolean
 */
public static Boolean isArray(Class<?> clazz) {
    return clazz.isArray();
}