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.metaparadigm.jsonrpc.ArraySerializer.java

@Override
public boolean canSerialize(Class clazz, Class jsonClazz) {
    Class cc = clazz.getComponentType();
    return (super.canSerialize(clazz, jsonClazz)
            || ((jsonClazz == null || jsonClazz == JSONArray.class) && (clazz.isArray() && !cc.isPrimitive())));
}

From source file:com.jetyun.pgcd.rpc.serializer.impl.BeanSerializer.java

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

From source file:io.github.benas.jpopulator.impl.PopulatorImpl.java

/**
 * This method checks if the given type is a java built-in collection type (ie, array, List, Set, Map, etc).
 *
 * @param type the type that the method should check
 * @return true if the given type is a java built-in collection type
 *//*from  ww w . j  a  va 2s.c om*/
private boolean isCollectionType(final Class<?> type) {
    return type.isArray() || Map.class.isAssignableFrom(type) || Collection.class.isAssignableFrom(type);
}

From source file:org.nabucco.alfresco.enhScriptEnv.common.script.converter.rhino.NativeArrayConverter.java

/**
 *
 * {@inheritDoc}/*from  w w w.j a  v  a 2 s .co m*/
 */
@Override
public int getForScriptConversionConfidence(final Class<?> valueInstanceClass, final Class<?> expectedClass) {
    final int confidence;
    if ((valueInstanceClass.isArray() || Collection.class.isAssignableFrom(valueInstanceClass))
            && expectedClass.isAssignableFrom(NativeArray.class)) {
        confidence = HIGHEST_CONFIDENCE;
    } else {
        confidence = LOWEST_CONFIDENCE;
    }
    return confidence;
}

From source file:de.huxhorn.sulky.plist.impl.PropertyListWriter.java

private void writeValue(XMLStreamWriter writer, Object value) throws XMLStreamException {
    if (value == null) {
        return;/*w ww  . j a  va  2  s.  c om*/
    }
    if (value instanceof String) {
        StaxUtilities.writeSimpleTextNode(writer, null, null, STRING_NODE, (String) value);
        return;
    }
    if (value instanceof Boolean) {
        Boolean bool = (Boolean) value;
        if (bool) {
            StaxUtilities.writeEmptyElement(writer, null, null, TRUE_NODE);
        } else {
            StaxUtilities.writeEmptyElement(writer, null, null, FALSE_NODE);
        }
        return;
    }

    if (value instanceof Character) {
        StaxUtilities.writeSimpleTextNode(writer, null, null, STRING_NODE, value.toString());
        return;
    }

    if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) {
        Number number = (Number) value;
        StaxUtilities.writeSimpleTextNode(writer, null, null, INTEGER_NODE, Long.toString(number.longValue()));
        return;
    }

    if (value instanceof Float || value instanceof Double) {
        Number number = (Number) value;
        StaxUtilities.writeSimpleTextNode(writer, null, null, REAL_NODE, Double.toString(number.doubleValue()));
        return;
    }

    if (value instanceof byte[]) {
        byte[] data = (byte[]) value;
        writeData(writer, data);
        return;
    }

    if (value instanceof Date) {
        Date date = (Date) value;
        writeDate(writer, date);
        return;
    }

    if (value instanceof Map) {
        Map map = (Map) value;
        writeDict(writer, map);
        return;
    }

    if (value instanceof Collection) {
        Collection collection = (Collection) value;
        writeArray(writer, collection);
        return;
    }

    Class valueClass = value.getClass();
    if (valueClass.isArray()) {
        List<?> list;
        // we handled byte[] already
        if (value instanceof short[]) {
            short[] array = (short[]) value;
            ArrayList<Short> arrayList = new ArrayList<Short>(array.length);
            for (short v : array) {
                arrayList.add(v);
            }
            list = arrayList;
        } else if (valueClass == int[].class) {
            int[] array = (int[]) value;
            ArrayList<Integer> arrayList = new ArrayList<Integer>(array.length);
            for (int v : array) {
                arrayList.add(v);
            }
            list = arrayList;
        } else if (valueClass == long[].class) {
            long[] array = (long[]) value;
            ArrayList<Long> arrayList = new ArrayList<Long>(array.length);
            for (long v : array) {
                arrayList.add(v);
            }
            list = arrayList;
        } else if (valueClass == float[].class) {
            float[] array = (float[]) value;
            ArrayList<Float> arrayList = new ArrayList<Float>(array.length);
            for (float v : array) {
                arrayList.add(v);
            }
            list = arrayList;
        } else if (valueClass == double[].class) {
            double[] array = (double[]) value;
            ArrayList<Double> arrayList = new ArrayList<Double>(array.length);
            for (double v : array) {
                arrayList.add(v);
            }
            list = arrayList;
        } else if (valueClass == boolean[].class) {
            boolean[] array = (boolean[]) value;
            ArrayList<Boolean> arrayList = new ArrayList<Boolean>(array.length);
            for (boolean v : array) {
                arrayList.add(v);
            }
            list = arrayList;
        } else if (valueClass == char[].class) {
            char[] array = (char[]) value;
            String s = new String(array);
            StaxUtilities.writeSimpleTextNode(writer, null, null, STRING_NODE, s);
            return;
        } else {
            list = Arrays.asList((Object[]) value);
            // special handling of container Object[]
        }
        writeArray(writer, list);
        return;
    }

    if (logger.isDebugEnabled())
        logger.debug("No suitable conversion found for {}. Will save it as string.", valueClass.getName());
    StaxUtilities.writeSimpleTextNode(writer, null, null, STRING_NODE, value.toString());
}

From source file:org.arrow.data.neo4j.store.impl.ProcessInstanceStoreImpl.java

/**
 * {@inheritDoc}/*ww w .  jav  a2  s  .  c  o  m*/
 */
private ProcessInstance store(BpmnNodeEntitySpecification event, Map<String, Object> map, SubProcessEntity sub,
        ProcessInstance parentPi) {

    GraphDatabaseAPI api = (GraphDatabaseAPI) template.getGraphDatabaseService();
    Transaction transaction = api.tx().unforced().begin();
    try {

        Node eventNode = template.getPersistentState(event);

        Assert.notNull(eventNode, "start event must not be null");
        Assert.notNull(map, "variables map must not be null");

        final Node node = getProcessInstance();

        Node processNode;
        if (sub instanceof CallActivityTask || sub == null) {

            if (sub != null) {
                Node processTrigger = template.getPersistentState(sub);
                node.createRelationshipTo(processTrigger, DynamicRelationshipType.withName("PROCESS_TRIGGER"));
            }

            Iterable<Relationship> relationships;

            if (event instanceof ReceiveTask) {
                MessageEventDefinition definition = ((ReceiveTask) event).getMessageEventDefinition();
                Node source = template.getPersistentState(definition);

                relationships = source.getRelationships(Direction.OUTGOING,
                        DynamicRelationshipType.withName("PROCESS"));
            } else {
                relationships = eventNode.getRelationships(Direction.OUTGOING,
                        DynamicRelationshipType.withName("PROCESS_OF_STARTEVENT"));
            }

            processNode = relationships.iterator().next().getEndNode();
        } else {
            processNode = template.getPersistentState(sub);
        }

        transaction.acquireWriteLock(processNode);

        for (String key : map.keySet()) {
            Object value = map.get(key);
            Class<?> cls = value.getClass();

            if (cls.isArray() || ClassUtils.isPrimitiveOrWrapper(cls)) {
                node.setProperty("variables-" + key, value);
            } else if (conversionService.canConvert(cls, String.class)) {
                value = conversionService.convert(value, String.class);
                node.setProperty("variables-" + key, value);
                node.setProperty("variables-" + key + "-type", cls.getName());
            } else {
                node.setProperty("variables-" + key, toXml(value));
                node.setProperty("variables-" + key + "-type", cls.getName());
            }
        }

        if (parentPi != null) {
            Node parentPiNode = template.getPersistentState(parentPi);
            node.createRelationshipTo(parentPiNode,
                    DynamicRelationshipType.withName("PARENT_PROCESS_INSTANCE"));
        }

        node.setProperty("key", processNode.getProperty("id"));
        node.createRelationshipTo(processNode, DynamicRelationshipType.withName("PROCESS"));

        transaction.success();
        return executionService.data().processInstance().findOne(node.getId());
    } catch (Throwable throwable) {
        transaction.failure();
        throw new RuntimeException(throwable);
    } finally {
        transaction.close();
    }

}

From source file:com.wantscart.jade.provider.jdbc.PreparedStatementCallbackReturnId.java

public PreparedStatementCallbackReturnId(PreparedStatementSetter setter, Class<?> returnType) {
    this.setter = setter;
    if (returnType.isPrimitive()) {
        returnType = ClassUtils.primitiveToWrapper(returnType);
    }/*w w  w . j  av a2  s  . c o  m*/
    this.returnType = returnType;
    Class<?> idType = returnType;
    if (returnType.isArray()) {
        idType = returnType.getComponentType();
    }
    this.idType = idType;
    if (idType.isPrimitive()) {
        idType = ClassUtils.primitiveToWrapper(idType);
    }
    this.wrappedIdType = idType;
    this.mapper = new SingleColumnRowMapper(idType);
    if (wrappedIdType != Integer.class && wrappedIdType != Long.class && wrappedIdType != Number.class) {
        throw new IllegalArgumentException(
                "wrong return type(int/long type or its array type only): " + returnType);
    }
}

From source file:de.escalon.hypermedia.action.ActionInputParameter.java

public Object[] getCallValues() {
    Object[] callValues;//from w w  w.j a  v a2 s.  com
    if (!isArrayOrCollection()) {
        throw new UnsupportedOperationException("parameter is not an array or collection");
    }
    Object callValue = getCallValue();
    if (callValue == null) {
        callValues = new Object[0];
    } else {
        Class<?> parameterType = getParameterType();
        if (parameterType.isArray()) {
            callValues = (Object[]) callValue;
        } else {
            callValues = ((Collection<?>) callValue).toArray();
        }
    }
    return callValues;
}

From source file:de.micromata.genome.util.strings.ReducedReflectionToStringBuilder.java

/**
 * Append fields in internal.//from   w  w  w  .  j  av a2  s  .c  om
 *
 * @param clazz the clazz
 * @return true, if successful
 */
protected boolean appendFieldsInInternal(Class<?> clazz) {

    registerObject(getObject());
    if (clazz.isArray()) {
        this.reflectionAppendArray(this.getObject());
        return false;
    }
    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        String fieldName = field.getName();
        if (this.accept(field) == false) {
            continue;
        }

        try {
            // Warning: Field.get(Object) creates wrappers objects
            // for primitive types.
            Object fieldValue = this.getValue(field);
            if (isObjectRegistered(fieldValue) == true && field.getType().isPrimitive() == false) {
                this.getStringBuffer().append(fieldName).append("=");
                this.appendAsObjectToString(fieldValue);
                this.getStringBuffer().append(",");

            } else {
                this.append(fieldName, fieldValue);
            }
        } catch (IllegalAccessException ex) {
            // this can't happen. Would get a Security exception
            // instead
            // throw a runtime exception in case the impossible
            // happens.
            throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
        }
    }
    return true;
}

From source file:com.fitbur.testify.integration.IntegrationTestVerifier.java

@Override
public void configuration() {
    doPrivileged((PrivilegedAction<Object>) () -> {
        String testClassName = testContext.getTestClassName();
        CutDescriptor cutDescriptor = testContext.getCutDescriptor();
        Collection<FieldDescriptor> fieldDescriptors = testContext.getFieldDescriptors().values();

        if (testContext.getCutCount() == 1) {
            checkState(testContext.getConstructorCount() == 1,
                    "Class under test '%s' defined in test class '%s' has %s constructors. "
                            + "Please insure that the class under test has one and only one constructor.",
                    cutDescriptor.getTypeName(), testClassName, testContext.getConstructorCount());
        }/*from ww  w .  j ava 2s . c om*/
        // insure that only one field has Cut annotation on it.
        if (testContext.getCutCount() > 1) {
            checkState(false, "Found more than one class under test in test class %s. Please insure "
                    + "that only one field is annotated with @Cut.", testClassName);
        }

        //insure that there is a field annotated with @Cut defined or one or more
        //fields annotated with @Real or @Inject
        if (testContext.getCutCount() == 0 && fieldDescriptors.isEmpty()) {
            checkState(false,
                    "Test class '%s' does not define a field annotated with @Cut "
                            + "nor does it define field(s) annotated with @Real or @Inject. "
                            + "Please insure the test class defines a single field annotated "
                            + "with @Cut or defines at least one field annotated with @Real " + "or @Inject.",
                    testClassName);
        }

        //insure need providers have default constructors.
        testContext.getAnnotations(Need.class).parallelStream().map(Need::value).forEach(p -> {
            try {
                p.getDeclaredConstructor();
            } catch (NoSuchMethodException e) {
                checkState(false,
                        "Need provider '%s' defined in test class '%s' does not have a "
                                + "zero argument default constructor. Please insure that the need "
                                + "provider defines an accessible zero argument default constructor.",
                        testClassName, p.getSimpleName());
            }
        });

        fieldDescriptors.parallelStream().forEach(p -> {

            Field field = p.getField();
            Class<?> fieldType = p.getType();
            String fieldName = p.getName();
            String fieldTypeName = p.getTypeName();

            checkState(!fieldType.isArray(),
                    "Field '%s' in test class '%s' can not be configured because '%s'"
                            + " is an array. Please consider using a List instead of arrays.",
                    fieldName, testClassName, fieldTypeName);
            Fake fake = field.getDeclaredAnnotation(Fake.class);
            if (fake != null) {
                checkState(!isFinal(fieldType.getModifiers()),
                        "Can not fake field '%s' in test class '%s' because '%s'" + " is a final class.",
                        fieldName, testClassName, fieldTypeName);
            }

            Real real = field.getDeclaredAnnotation(Real.class);
            if (real != null && real.value()) {
                checkState(!isFinal(fieldType.getModifiers()),
                        "Can not create delegated fake of field '%s' in test class '%s' "
                                + "because '%s' is a final class.",
                        fieldName, testClassName, fieldTypeName);
            }
        });

        return null;
    });
}