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:Main.java

/**
 * get generic class by actual type argument index.
 *///from  w ww .jav a 2  s  . c  o m
public static Class<?> getGenericClass(Class<?> cls, int actualTypeArgIndex) {
    try {
        ParameterizedType parameterizedType;
        if (cls.getGenericInterfaces().length > 0
                && cls.getGenericInterfaces()[0] instanceof ParameterizedType) {
            parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]);
        } else if (cls.getGenericSuperclass() instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) cls.getGenericSuperclass();
        } else {
            parameterizedType = null;
        }
        if (parameterizedType != null) {
            Object genericClass = parameterizedType.getActualTypeArguments()[actualTypeArgIndex];
            if (genericClass instanceof ParameterizedType) {
                return (Class<?>) ((ParameterizedType) genericClass).getRawType();
            } else if (genericClass instanceof GenericArrayType) {
                Class<?> componentType = (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
                if (componentType.isArray()) {
                    return componentType;
                } else {
                    return Array.newInstance(componentType, 0).getClass();
                }
            } else if (genericClass instanceof Class) {
                return (Class<?>) genericClass;
            }
        }
    } catch (Exception e) {
    }
    if (cls.getSuperclass() != null && cls.getSuperclass() != Object.class) {
        return getGenericClass(cls.getSuperclass(), actualTypeArgIndex);
    } else {
        throw new IllegalArgumentException(cls.getName() + " generic type undefined!");
    }
}

From source file:com.adobe.acs.commons.data.Spreadsheet.java

private static Class getArrayType(Class clazz) {
    if (clazz.isArray()) {
        return clazz;
    } else {/*from w w  w.  j  a va2 s .c o m*/
        return Array.newInstance(clazz, 0).getClass();
    }
}

From source file:kelly.util.BeanUtils.java

/**
 * Check if the given type represents a "simple" property:
 * a primitive, a String or other CharSequence, a Number, a Date,
 * a URI, a URL, a Locale, a Class, or a corresponding array.
 * <p>Used to determine properties to check for a "simple" dependency-check.
 * @param clazz the type to check/*from w ww .j a  v  a 2  s. com*/
 * @return whether the given type represents a "simple" property
 * @see org.springframework.beans.factory.support.RootBeanDefinition#DEPENDENCY_CHECK_SIMPLE
 * @see org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#checkDependencies
 */
public static boolean isSimpleProperty(Class<?> clazz) {
    Validate.notNull(clazz, "Class must not be null");
    return isSimpleValueType(clazz) || (clazz.isArray() && isSimpleValueType(clazz.getComponentType()));
}

From source file:Main.java

/**
 * Returns o.toString() unless it throws an exception (which causes it to be
 * stored in unrenderableClasses) or already was present in
 * unrenderableClasses. If so, the same string is returned as would have
 * been returned by Object.toString(). Arrays get special treatment as they
 * don't have usable toString methods./*from   w  w  w .  j  a  v  a 2  s .  co  m*/
 * 
 * @param o
 *            incoming object to render.
 * @return
 */

public static String render(Object o) {
    if (o == null) {
        return String.valueOf(o);
    }
    Class<?> objectClass = o.getClass();

    if (unrenderableClasses.containsKey(objectClass) == false) {
        try {
            if (objectClass.isArray()) {
                return renderArray(o, objectClass).toString();
            } else {
                return o.toString();
            }
        } catch (Exception e) {
            Long now = new Long(System.currentTimeMillis());

            System.err.println(
                    "Disabling exception throwing class " + objectClass.getName() + ", " + e.getMessage());

            unrenderableClasses.put(objectClass, now);
        }
    }
    String name = o.getClass().getName();
    return name + "@" + Integer.toHexString(o.hashCode());
}

From source file:com.netspective.sparx.util.HttpUtils.java

public static void assignParamToInstance(HttpServletRequest req, XmlDataModelSchema schema, Object instance,
        String paramName, String defaultValue)
        throws IllegalAccessException, InvocationTargetException, DataModelException {
    boolean required = false;
    if (paramName.endsWith("!")) {
        required = true;//from   w  w w  .  j a  v  a  2s.  co m
        paramName = paramName.substring(0, paramName.length() - 1);
    }

    Method method = (Method) schema.getAttributeSetterMethods().get(paramName);
    if (method != null) {
        Class[] args = method.getParameterTypes();
        if (args.length == 1) {
            Class arg = args[0];
            if (java.lang.String.class.equals(arg) && arg.isArray()) {
                String[] paramValues = req.getParameterValues(paramName);
                if ((paramValues == null || paramValues.length == 0) && required)
                    throw new ServletParameterRequiredException(
                            "Servlet parameter list '" + paramName + "' is required but not available.");
                method.invoke(instance, new Object[] { paramValues });
            } else {
                XmlDataModelSchema.AttributeSetter as = (XmlDataModelSchema.AttributeSetter) schema
                        .getAttributeSetters().get(paramName);
                String paramValue = req.getParameter(paramName);
                if (paramValue == null) {
                    if (required)
                        throw new ServletParameterRequiredException(
                                "Servlet parameter '" + paramName + "' is required but not available.");

                    paramValue = defaultValue;
                }
                as.set(null, instance, paramValue);
            }
        } else if (log.isDebugEnabled())
            log.debug("Attempting to assign '" + paramName + "' to a method in '" + instance.getClass()
                    + "' but the method has more than one argument.");
    } else if (log.isDebugEnabled())
        log.debug("Attempting to assign '" + paramName + "' to a method in '" + instance.getClass()
                + "' but there is no mutator available.");
}

From source file:com.dianping.lion.util.UrlUtils.java

public static String resolveUrl(Map<String, ?> parameters, String... includes) {
    StringBuilder url = new StringBuilder();
    int index = 0;
    try {// w  w w . j av  a2s .c  o  m
        if (parameters != null) {
            for (Entry<String, ?> entry : parameters.entrySet()) {
                Collection<Object> paramValues = new ArrayList<Object>();
                Object paramValue = entry.getValue();
                if (ArrayUtils.isEmpty(includes) || ArrayUtils.contains(includes, entry.getKey())) {
                    Class<? extends Object> paramClass = paramValue.getClass();
                    if (Collection.class.isInstance(paramValue)) {
                        paramValues.addAll((Collection<?>) paramValue);
                    } else if (paramClass.isArray()) {
                        Object[] valueArray = (Object[]) paramValue;
                        for (Object value : valueArray) {
                            paramValues.add(value);
                        }
                    } else {
                        paramValues.add(paramValue);
                    }
                    for (Object value : paramValues) {
                        url.append(index++ == 0 ? "" : "&").append(entry.getKey()).append("=")
                                .append(URLEncoder.encode(value.toString(), "utf-8"));
                    }
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return url.toString();
}

From source file:net.mojodna.searchable.util.SearchableUtils.java

/**
 * @param clazz/*  www. j  a  v a  2s  . c om*/
 * @param propertyName
 * @return Whether this property may contain multiple values (i.e. is a Collection).
 */
public static final boolean isMultiValued(final Class<?> clazz, final String propertyName) {
    final Class<?> returnType = getReturnType(clazz, propertyName);
    if (returnType.isArray()) {
        return true;
    }
    if (Iterable.class.isAssignableFrom(returnType)) {
        return true;
    }
    return false;
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

public static JSONSerializable deSerialize(Class clz, JSONObject jsonObj)
        throws JSONSerializationException, JSONException {
    Iterator iter = jsonObj.keys();

    if (!JSONSerializable.class.isAssignableFrom(clz)) {
        throw new JSONSerializationException(clz + " is not an instance of " + JSONSerializable.class);
    }/*from   w  w w  . j ava2  s .  c  om*/

    JSONSerializable retObj;
    try {
        retObj = (JSONSerializable) clz.newInstance();
    } catch (Exception e1) {
        throw new JSONSerializationException(
                "trouble with no-arg instantiation of " + clz.toString() + ": " + e1.getMessage(), e1);
    }

    if (JSONExternalizable.class.isAssignableFrom(clz)) {
        ((JSONExternalizable) retObj).fromJSON(jsonObj);
        return retObj;
    }

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

        try {
            Field f = clz.getDeclaredField(key);
            if (f != null) {
                f.setAccessible(true);
                Class type = f.getType();

                if (type.isArray()) {
                    JSONArray array = jsonObj.getJSONArray(key);
                    int len = array.length();
                    Class cls = type.getComponentType();

                    Object newArray = Array.newInstance(cls, len);
                    for (int k = 0; k < len; ++k) {
                        loadObject(newArray, cls, k, array);
                    }
                    f.set(retObj, newArray);
                } else {
                    loadObject(retObj, f, jsonObj);
                }
            }
        } catch (Exception e) {
            throw new JSONSerializationException(e.getMessage(), e);
        }
    }

    return retObj;
}

From source file:jp.furplag.util.commons.ObjectUtils.java

/**
 * substitute for {@link java.lang.Class#newInstance()}.
 *
 * @param type the Class object, return false if null.
 * @return empty instance of specified {@link java.lang.Class}.
 * @throws IllegalArgumentException/*from  ww  w  .j av  a2s  .co  m*/
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws ClassNotFoundException
 * @throws NegativeArraySizeException
 */
@SuppressWarnings("unchecked")
public static <T> T newInstance(final Class<T> type) throws InstantiationException {
    if (type == null)
        return null;
    if (type.isArray())
        return (T) Array.newInstance(type.getComponentType(), 0);
    if (Void.class.equals(ClassUtils.primitiveToWrapper(type))) {
        try {
            Constructor<Void> c = Void.class.getDeclaredConstructor();
            c.setAccessible(true);

            return (T) c.newInstance();
        } catch (SecurityException e) {
        } catch (NoSuchMethodException e) {
        } catch (InvocationTargetException e) {
        } catch (IllegalAccessException e) {
        }

        return null;
    }

    if (type.isInterface()) {
        if (!Collection.class.isAssignableFrom(type))
            throw new InstantiationException(
                    "could not create instance, the type \"" + type.getName() + "\" is an interface.");
        if (List.class.isAssignableFrom(type))
            return (T) Lists.newArrayList();
        if (Map.class.isAssignableFrom(type))
            return (T) Maps.newHashMap();
        if (Set.class.isAssignableFrom(type))
            return (T) Sets.newHashSet();
    }

    if (type.isPrimitive()) {
        if (boolean.class.equals(type))
            return (T) Boolean.FALSE;
        if (char.class.equals(type))
            return (T) Character.valueOf(Character.MIN_VALUE);

        return (T) NumberUtils.valueOf("0", (Class<? extends Number>) type);
    }
    if (ClassUtils.isPrimitiveOrWrapper(type))
        return null;
    if (Modifier.isAbstract(type.getModifiers()))
        throw new InstantiationException(
                "could not create instance, the type \"" + type.getName() + "\" is an abstract class.");

    try {
        Constructor<?> c = type.getDeclaredConstructor();
        c.setAccessible(true);

        return (T) c.newInstance();
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    } catch (InvocationTargetException e) {
    } catch (IllegalAccessException e) {
    }

    throw new InstantiationException("could not create instance, the default constructor of \"" + type.getName()
            + "()\" is not accessible ( or undefined ).");
}

From source file:microsoft.exchange.webservices.data.misc.MapiTypeConverterMapEntry.java

/**
 * Gets the dim. If `array' is an array object returns its dimensions;
 * otherwise returns 0/*from  w w w.j a  v a  2  s .  co m*/
 *
 * @param array the array
 * @return the dim
 */
public static int getDim(Object array) {
    int dim = 0;
    Class<?> cls = array.getClass();
    while (cls.isArray()) {
        dim++;
        cls = cls.getComponentType();
    }
    return dim;
}