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:springfox.documentation.swagger.readers.parameter.ParameterMultiplesReader.java

@Override
public void apply(ParameterContext context) {

    MethodParameter methodParameter = context.methodParameter();
    ApiParam apiParam = methodParameter.getParameterAnnotation(ApiParam.class);

    Boolean allowMultiple;/*www  .j  a va 2s. co  m*/
    Class<?> parameterType = methodParameter.getParameterType();
    if (null != apiParam && !(parameterType != null && parameterType.isArray()
            && parameterType.getComponentType().isEnum())) {
        allowMultiple = apiParam.allowMultiple();
        context.parameterBuilder().allowMultiple(allowMultiple);
    }
}

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

/**
 * get name. java.lang.Object[][].class => "java.lang.Object[][]"
 * /*w  w w. ja va  2s . c o m*/
 * @param c
 *            class.
 * @return name.
 */
public static String getName(Class<?> c) {
    if (c.isArray()) {
        StringBuilder sb = new StringBuilder();
        do {
            sb.append("[]");
            c = c.getComponentType();
        } while (c.isArray());

        return c.getName() + sb.toString();
    }
    return c.getName();
}

From source file:org.al.swagger.v2.AbstractSpecCollector.java

public Object createSchemaObject(Class<?> aClass) {
    if (aClass.isArray()) {
        GenericSwaggerSchema schema = new GenericSwaggerSchema();
        schema.setType("array");
        schema.setCollectionFormat("csv");
        schema.setItems(createSchemaObject(aClass.getComponentType()));
        return schema;

    } else if (JDKPrimitiveType.isPrimitiveType(aClass)) {

        SchemaGenerator generator = SimpleTypeFactory.getInstance().getSchemaGenerator(aClass);
        if (generator != null) {
            return generator.generateSchema(aClass);
        } else {/*from w  w  w  .  j a va2  s  .  c  o  m*/
            throw new RuntimeException("Type " + aClass + " not supporeted");

        }

    } else {

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

        Map<String, Object> properties = new LinkedHashMap<>();
        schemaMap.put("properties", properties);

        List<Field> fields = Stream.of(aClass.getDeclaredFields())
                .filter(f -> !f.isAnnotationPresent(JsonIgnore.class) && !Modifier.isStatic(f.getModifiers()))
                .collect(Collectors.toList());
        for (Field f : fields) {
            if (f.getName().equalsIgnoreCase("rowId")) {
                properties.put(f.getName(), SimpleTypeFactory.getInstance().getSchemaGenerator(String.class)
                        .generateSchema(String.class));
            } else {
                Object schemaObject = createSchemaObject(f.getType());
                properties.put(f.getName(), schemaObject);
            }

        }

        return schemaMap;
    }

}

From source file:com.dinstone.ut.faststub.internal.StubMethodInvocation.java

/**
 * {@inheritDoc}/* www  .  j  a  va 2 s  . c o m*/
 * 
 */
public Object invoke(Method method, Object[] args) throws Throwable {
    ApplicationContext stubContext = getStubContext(method);
    Object retObj = stubContext.getBean(method.getName());
    // handle exception
    handleException(retObj);

    // handle array object
    Class<?> retType = method.getReturnType();
    if (retType.isArray() && retObj instanceof List<?>) {
        List<?> list = (List<?>) retObj;
        int len = list.size();
        Object arrObj = Array.newInstance(retType.getComponentType(), len);
        for (int i = 0; i < len; i++) {
            Array.set(arrObj, i, list.get(i));
        }
        return arrObj;
    }

    return retObj;
}

From source file:com.ebay.jetstream.epl.EPLUtilities.java

/**
 * Expects and distinguishes map, array, list and plain bean. Also recognizes Jetstream attributes.
 * /*  w  ww. j a v a  2  s.  co m*/
 * @param bean
 * @param name
 * @return
 * @throws SecurityException
 * @throws NoSuchMethodException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
@SuppressWarnings("unchecked")
private static Object getBeanEntry(Object bean, String name) throws SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    if (bean == null || name == null || name.length() < 1) {
        return null;
    }
    if (bean instanceof Map) {
        return ((Map) bean).get(name);
    }
    Class cls = bean.getClass();
    try {
        Integer index = Integer.valueOf(name);
        if (cls.isArray()) {
            return ((Object[]) bean)[index];
        }
        Method getter = cls.getMethod("get", int.class); // trying List.get
        return getter.invoke(bean, index);
    } catch (NumberFormatException ex) {
        // not integer, trying to get a bean property...
    }
    try {
        // some wsdl types don't follow bean specs and use direct naming
        Method getter = cls.getMethod(name);
        return getter.invoke(bean, (Object[]) null);
    } catch (NoSuchMethodException ex) {
    }

    // attributes retriever
    if (bean instanceof List) {
        List list = (List) bean;
        for (Object entry : list) {
            Object value = getBeanEntry(entry, name);
            if (value != null) {
                return value;
            }
        }
    }
    try {
        // trying a particular attribute having this name
        Object ret = cls.getMethod("getName").invoke(bean, (Object[]) null);
        if (ret instanceof String) {
            if (name.equals(ret)) {
                return cls.getMethod("getValue").invoke(bean, (Object[]) null);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("getBeanEntry skipped attribute '" + ret + "' for bean '" + bean + "' of class '"
                        + cls.getName() + "'", LOGGING_COMPONENT_NAME);
            }
        }
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("getBeanEntry failed to retrieve potential attribute '" + name + "' for bean '" + bean
                    + "' of class '" + cls.getName() + "'. Exception: " + ex, LOGGING_COMPONENT_NAME);
        }
    }

    // last chance: trying getter
    StringBuffer buf = new StringBuffer();
    buf.append("get");
    buf.append(name.substring(0, 1).toUpperCase());
    buf.append(name.substring(1));
    String methodName = buf.toString();
    try {
        return cls.getMethod(methodName).invoke(bean, (Object[]) null);
    } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("getBeanEntry failed to call method '" + methodName + "' for bean '" + bean
                    + "' of class '" + cls.getName() + "'. Exception: " + ex, LOGGING_COMPONENT_NAME);
        }
    }
    return null;
}

From source file:ClassReader.java

private static void addDescriptor(StringBuffer b, Class c) {
    if (c.isPrimitive()) {
        if (c == void.class) {
            b.append('V');
        } else if (c == int.class) {
            b.append('I');
        } else if (c == boolean.class) {
            b.append('Z');
        } else if (c == byte.class) {
            b.append('B');
        } else if (c == short.class) {
            b.append('S');
        } else if (c == long.class) {
            b.append('J');
        } else if (c == char.class) {
            b.append('C');
        } else if (c == float.class) {
            b.append('F');
        } else if (c == double.class) {
            b.append('D');
        }//from  w  w  w .ja v a  2  s .co  m
    } else if (c.isArray()) {
        b.append('[');
        addDescriptor(b, c.getComponentType());
    } else {
        b.append('L').append(c.getName().replace('.', '/')).append(';');
    }
}

From source file:jef.tools.ArrayUtils.java

/**
 * ??/*w w  w. java 2s  . co  m*/
 * java.util.Arrays??????9???
 * 
 * @param a1
 *            Object
 * @param a2
 *            Object,
 * @return
 * @see java.util.Arrays#equals(boolean[], boolean[])
 * @see java.util.Arrays#equals(byte[], byte[])
 * @see java.util.Arrays#equals(char[], char[])
 * @see java.util.Arrays#equals(double[], double[])
 * @see java.util.Arrays#equals(float[], float[])
 * @see java.util.Arrays#equals(int[], int[])
 * @see java.util.Arrays#equals(long[], long[])
 * @see java.util.Arrays#equals(short[], short[])
 * @see java.util.Arrays#equals(Object[], Object[])
 * @throws IllegalArgumentException
 *             ?
 */
public static boolean equals(Object a1, Object a2) {
    if (a1 == a2)
        return true;
    if (a1 == null || a2 == null)
        return false;
    Class<?> clz1 = a1.getClass();
    Class<?> clz2 = a2.getClass();
    if (!clz1.isArray() || !clz2.isArray()) {
        throw new IllegalArgumentException("must comapre between two Array.");
    }
    clz1 = clz1.getComponentType();
    clz2 = clz2.getComponentType();
    if (clz1.isPrimitive() != clz2.isPrimitive()) {
        return false;
    }
    if (clz1 == int.class) {
        return Arrays.equals((int[]) a1, (int[]) a2);
    } else if (clz1 == short.class) {
        return Arrays.equals((short[]) a1, (short[]) a2);
    } else if (clz1 == long.class) {
        return Arrays.equals((long[]) a1, (long[]) a2);
    } else if (clz1 == float.class) {
        return Arrays.equals((float[]) a1, (float[]) a2);
    } else if (clz1 == double.class) {
        return Arrays.equals((double[]) a1, (double[]) a2);
    } else if (clz1 == boolean.class) {
        return Arrays.equals((boolean[]) a1, (boolean[]) a2);
    } else if (clz1 == byte.class) {
        return Arrays.equals((byte[]) a1, (byte[]) a2);
    } else if (clz1 == char.class) {
        return Arrays.equals((char[]) a1, (char[]) a2);
    } else {
        return Arrays.equals((Object[]) a1, (Object[]) a2);
    }
}

From source file:com.metaparadigm.jsonrpc.ReferenceSerializer.java

@Override
public boolean canSerialize(Class clazz, Class jsonClazz) {
    return (!clazz.isArray() && !clazz.isPrimitive() && !clazz.isInterface()
            && (bridge.isReference(clazz) || bridge.isCallableReference(clazz))
            && (jsonClazz == null || jsonClazz == JSONObject.class));
}

From source file:io.github.theangrydev.yatspeczohhakplugin.json.JsonCollectionsParameterCoercer.java

@Override
public Object coerceParameter(Type type, String stringToParse) {
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Class<?> rawType = (Class<?>) parameterizedType.getRawType();
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        return coerceParameterizedType(stringToParse, actualTypeArguments, rawType);
    } else if (type instanceof Class) {
        Class<?> targetType = ClassUtils.primitiveToWrapper((Class<?>) type);
        if (targetType.isArray()) {
            return coerceCollection(stringToParse, targetType.getComponentType(), ArrayBuilder::new);
        }/*from   w w w  .  jav a2 s  .  c o  m*/
        return defaultParameterCoercer.coerceParameter(targetType, stringToParse);
    } else {
        throw new IllegalArgumentException(format("Cannot interpret '%s' as a '%s'", stringToParse, type));
    }
}

From source file:com.bstek.dorado.data.JsonUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object internalToJavaCollection(ArrayNode arrayNode, AggregationDataType dataType,
        Class<Collection<?>> targetType, boolean proxy, JsonConvertContext context) throws Exception {
    Class<Collection> creationType = null;
    if (dataType != null) {
        creationType = (Class<Collection>) dataType.getCreationType();
    }//from www  . j ava  2  s .  c om

    boolean shouldConvertToArray = false;
    Collection collection = null;
    if (creationType != null) {
        if (targetType != null && !targetType.isAssignableFrom(creationType)) {
            throw new IllegalArgumentException("Java type mismatch. expect [" + targetType + "].");
        }

        if (!Collection.class.isAssignableFrom(creationType)) {
            if (creationType.isArray()) {
                shouldConvertToArray = true;
            } else {
                throw new IllegalArgumentException(
                        "Java type mismatch. expect [java.util.Collection] or [Array].");
            }
        } else {
            if (!Modifier.isAbstract(creationType.getModifiers())) {
                collection = creationType.newInstance();
            }
        }
    } else if (targetType != null) {
        if (targetType.isArray()) {
            shouldConvertToArray = true;
        } else if (!Modifier.isAbstract(targetType.getModifiers())) {
            collection = targetType.newInstance();
        } else if (Set.class.isAssignableFrom(targetType)) {
            collection = new HashSet<Object>();
        }
    }

    if (collection == null) {
        collection = new ArrayList<Object>();
    }

    boolean isFirstElement = true;
    DataType elementDataType = ((dataType != null) ? dataType.getElementDataType() : null);
    Iterator<JsonNode> it = arrayNode.iterator();
    while (it.hasNext()) {
        JsonNode jsonNode = it.next();
        if (jsonNode instanceof ObjectNode) {
            ObjectNode objectNode = (ObjectNode) jsonNode;
            if (isFirstElement && elementDataType == null) {
                String dataTypeName = JsonUtils.getString(objectNode, DATATYPE_PROPERTY);
                if (StringUtils.isNotEmpty(dataTypeName)) {
                    elementDataType = getDataType(dataTypeName, context);
                }
            }
            collection.add(
                    internalToJavaEntity(objectNode, (EntityDataType) elementDataType, null, proxy, context));
        } else if (jsonNode instanceof ValueNode) {
            collection.add(toJavaValue(((ValueNode) jsonNode), elementDataType, context));
        } else {
            throw new IllegalArgumentException("Value type mismatch. expect [JSON Value].");
        }
        isFirstElement = false;
    }

    if (context != null && context.getEntityListCollection() != null) {
        context.getEntityListCollection().add(collection);
    }

    if (shouldConvertToArray) {
        return collection.toArray();
    } else {
        if (dataType != null) {
            collection = EntityUtils.toEntity(collection, dataType);
        }
        return collection;
    }
}