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.jilk.ros.rosbridge.implementation.JSON.java

public static Class getFieldClass(Message parent, JSONObject jo, Field f, Registry<Class> r) {
    Class fc;
    fc = f.getType();/*from www.j  av  a2 s. co  m*/
    if (fc.isArray())
        fc = f.getType().getComponentType();
    if (Indication.isIndicated(f) && (jo != null)) {
        //fc = Indication.getIndication(parent,
        //        (String) jo.get(Indication.getIndicatorName(parent.getClass())));
        fc = r.lookup(parent.getClass(), (String) jo.get(Indication.getIndicatorName(parent.getClass())));
        //System.out.println("JSON.getFieldClass: parent class " + parent.getClass().getName() +
        //        " Indicator: " + Indication.getIndicatorName(parent.getClass()) + 
        //        " result: " + fc.getName());
    }
    return fc;
}

From source file:com.evolveum.midpoint.prism.util.CloneUtil.java

public static <T> T clone(T orig) {
    if (orig == null) {
        return null;
    }/*  ww  w. j  a v  a 2s  .  co  m*/
    Class<? extends Object> origClass = orig.getClass();
    if (ClassUtils.isPrimitiveOrWrapper(origClass)) {
        return orig;
    }
    if (origClass.isArray()) {
        return cloneArray(orig);
    }
    if (orig instanceof PolyString) {
        // PolyString is immutable
        return orig;
    }
    if (orig instanceof String) {
        // ...and so is String
        return orig;
    }
    if (orig instanceof QName) {
        // the same here
        return orig;
    }
    if (origClass.isEnum()) {
        return orig;
    }
    //        if (orig.getClass().equals(QName.class)) {
    //            QName origQN = (QName) orig;
    //            return (T) new QName(origQN.getNamespaceURI(), origQN.getLocalPart(), origQN.getPrefix());
    //        }
    if (orig instanceof RawType) {
        return (T) ((RawType) orig).clone();
    }
    if (orig instanceof Item<?, ?>) {
        return (T) ((Item<?, ?>) orig).clone();
    }
    if (orig instanceof PrismValue) {
        return (T) ((PrismValue) orig).clone();
    }
    if (orig instanceof ObjectDelta<?>) {
        return (T) ((ObjectDelta<?>) orig).clone();
    }
    if (orig instanceof ObjectDeltaType) {
        return (T) ((ObjectDeltaType) orig).clone();
    }
    if (orig instanceof ItemDelta<?, ?>) {
        return (T) ((ItemDelta<?, ?>) orig).clone();
    }
    if (orig instanceof Definition) {
        return (T) ((Definition) orig).clone();
    }
    /*
     * In some environments we cannot clone XMLGregorianCalendar because of this:
     * Error when cloning class org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl, will try serialization instead.
       * java.lang.IllegalAccessException: Class com.evolveum.midpoint.prism.util.CloneUtil can not access a member of
       * class org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl with modifiers "public"
     */
    if (orig instanceof XMLGregorianCalendar) {
        return (T) XmlTypeConverter.createXMLGregorianCalendar((XMLGregorianCalendar) orig);
    }
    if (orig instanceof Cloneable) {
        T clone = javaLangClone(orig);
        if (clone != null) {
            return clone;
        }
    }
    if (orig instanceof Serializable) {
        // Brute force
        if (PERFORMANCE_ADVISOR.isDebugEnabled()) {
            PERFORMANCE_ADVISOR.debug("Cloning a Serializable ({}). It could harm performance.",
                    orig.getClass());
        }
        return (T) SerializationUtils.clone((Serializable) orig);
    }
    throw new IllegalArgumentException("Cannot clone " + orig + " (" + origClass + ")");
}

From source file:com.hurence.logisland.connect.opc.CommonUtils.java

/**
 * Convert a java object to a {@link SchemaAndValue} data.
 *
 * @param value/*from   w w w . j a  v  a2  s . c o  m*/
 * @return
 */
public static SchemaAndValue convertToNativeType(final Object value) {

    Class<?> cls = value != null ? value.getClass() : Void.class;
    final ArrayList<Object> objs = new ArrayList<>();

    if (cls.isArray()) {
        final Object[] array = (Object[]) value;

        Schema arraySchema = null;

        for (final Object element : array) {
            SchemaAndValue tmp = convertToNativeType(element);
            if (arraySchema == null) {
                arraySchema = tmp.schema();
            }
            objs.add(tmp.value());
        }

        return new SchemaAndValue(SchemaBuilder.array(arraySchema), objs);
    }

    if (cls.isAssignableFrom(Void.class)) {
        return SchemaAndValue.NULL;
    } else if (cls.isAssignableFrom(String.class)) {
        return new SchemaAndValue(SchemaBuilder.string().optional(), value);
    } else if (cls.isAssignableFrom(Short.class)) {
        return new SchemaAndValue(SchemaBuilder.int16().optional(), value);
    } else if (cls.isAssignableFrom(Integer.class)) {

        return new SchemaAndValue(SchemaBuilder.int32().optional(), value);
    } else if (cls.isAssignableFrom(Long.class)) {

        return new SchemaAndValue(SchemaBuilder.int64().optional(), value);
    } else if (cls.isAssignableFrom(Byte.class)) {
        return new SchemaAndValue(SchemaBuilder.int8().optional(), value);
    } else if (cls.isAssignableFrom(Character.class)) {
        return new SchemaAndValue(SchemaBuilder.int32().optional(),
                value == null ? null : new Integer(((char) value)));
    } else if (cls.isAssignableFrom(Boolean.class)) {
        return new SchemaAndValue(SchemaBuilder.bool().optional(), value);
    } else if (cls.isAssignableFrom(Float.class)) {
        return new SchemaAndValue(SchemaBuilder.float32().optional(), value);
    } else if (cls.isAssignableFrom(BigDecimal.class)) {
        return new SchemaAndValue(SchemaBuilder.float64().optional(),
                value == null ? null : ((BigDecimal) value).doubleValue());
    } else if (cls.isAssignableFrom(Double.class)) {
        return new SchemaAndValue(SchemaBuilder.float64().optional(), value);
    } else if (cls.isAssignableFrom(Instant.class)) {
        return new SchemaAndValue(SchemaBuilder.int64().optional(),
                value == null ? null : ((Instant) value).toEpochMilli());

    }
    throw new SchemaBuilderException("Unknown type presented (" + cls + ")");

}

From source file:com.yukthi.utils.beans.PropertyMapper.java

/**
 * Called to check when property copy has to be done mismatching fields. Simple types like primitives, java core classes and arrays will be skipped.
 * @param type Type to be checked// w  ww  .ja  v a 2s  .  c  om
 * @return
 */
private static boolean isIgnorableType(Class<?> type) {
    if (type.isPrimitive() || type.getName().startsWith("java") || type.isArray()) {
        return true;
    }

    return false;
}

From source file:Main.java

/**
 * Get a list of the name of variables of the class received
 * @param klass Class to get the variable names
 * @return List<String>[] of length 3 with variable names: [0]: primitives, [1]: arrays, [2]: objects
 */// w w  w  .  j  a  v  a2  s. c om
public static List<String>[] getVariableNames(Class klass) {

    //array to return
    List<String>[] varNames = new List[3];
    for (int i = 0; i < 3; i++) {
        varNames[i] = new ArrayList<>();
    }

    //add all valid fields
    do {
        Field[] fields = klass.getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isTransient(field.getModifiers())) {

                //get the type
                Class type = field.getType();

                if (type.isPrimitive() || (type == Integer.class) || (type == Float.class)
                        || (type == Double.class) || (type == Boolean.class) || (type == String.class)) {
                    varNames[0].add(field.getName());
                } else if (type.isArray()) {
                    varNames[1].add(field.getName());
                } else {
                    varNames[2].add(field.getName());
                }
            }
        }

        klass = klass.getSuperclass();
    } while (klass != null);

    //return array
    return varNames;

}

From source file:com.sparkplatform.api.core.PropertyAsserter.java

/**
 * See {@link #assertBasicGetterSetterBehavior(Object,String)} method. Only difference is that here we accept an
 * explicit argument for the setter method.
 *
 * @param target   the object on which to invoke the getter and setter
 * @param property the property name, e.g. "firstName"
 * @param argument the property value, i.e. the value the setter will be invoked with
 *//*from w ww . java  2  s. c  o  m*/
public static void assertBasicGetterSetterBehavior(Object target, String property, Object argument) {
    try {
        PropertyDescriptor descriptor = new PropertyDescriptor(property, target.getClass());
        Object arg = argument;
        Class type = descriptor.getPropertyType();
        if (arg == null) {
            if (type.isArray()) {
                arg = Array.newInstance(type.getComponentType(), new int[] { TEST_ARRAY_SIZE });
            } else if (type.isEnum()) {
                arg = type.getEnumConstants()[0];
            } else if (TYPE_ARGUMENTS.containsKey(type)) {
                arg = TYPE_ARGUMENTS.get(type);
            } else {
                arg = invokeDefaultConstructorEvenIfPrivate(type);
            }
        }

        Method writeMethod = descriptor.getWriteMethod();
        Method readMethod = descriptor.getReadMethod();

        writeMethod.invoke(target, arg);
        Object propertyValue = readMethod.invoke(target);
        if (type.isPrimitive()) {
            assertEquals(property + " getter/setter failed test", arg, propertyValue);
        } else {
            assertSame(property + " getter/setter failed test", arg, propertyValue);
        }
    } catch (IntrospectionException e) {
        String msg = "Error creating PropertyDescriptor for property [" + property
                + "]. Do you have a getter and a setter?";
        log.error(msg, e);
        fail(msg);
    } catch (IllegalAccessException e) {
        String msg = "Error accessing property. Are the getter and setter both accessible?";
        log.error(msg, e);
        fail(msg);
    } catch (InvocationTargetException e) {
        String msg = "Error invoking method on target";
        log.error(msg, e);
        fail(msg);
    }
}

From source file:tools.xor.util.ClassUtil.java

public static int getDimensionCount(Object array) {
    int count = 0;
    Class<?> arrayClass = array.getClass();
    while (arrayClass.isArray()) {
        count++;//from w  w w  . ja v a  2s  .c  o  m
        arrayClass = arrayClass.getComponentType();
    }
    return count;
}

From source file:org.springmodules.cache.util.Reflections.java

/**
 * <p>//from ww w.j a v  a 2  s. co m
 * This method uses reflection to build a valid hash code.
 * </p>
 *
 * <p>
 * It uses <code>AccessibleObject.setAccessible</code> to gain access to
 * private fields. This means that it will throw a security exception if run
 * under a security manager, if the permissions are not set up correctly. It
 * is also not as efficient as testing explicitly.
 * </p>
 *
 * <p>
 * Transient members will not be used, as they are likely derived fields,
 * and not part of the value of the <code>Object</code>.
 * </p>
 *
 * <p>
 * Static fields will not be tested. Superclass fields will be included.
 * </p>
 *
 * @param obj
 *          the object to create a <code>hashCode</code> for
 * @return the generated hash code, or zero if the given object is
 *         <code>null</code>
 */
public static int reflectionHashCode(Object obj) {
    if (obj == null)
        return 0;

    Class targetClass = obj.getClass();
    if (Objects.isArrayOfPrimitives(obj) || Objects.isPrimitiveOrWrapper(targetClass)) {
        return Objects.nullSafeHashCode(obj);
    }

    if (targetClass.isArray()) {
        return reflectionHashCode((Object[]) obj);
    }

    if (obj instanceof Collection) {
        return reflectionHashCode((Collection) obj);
    }

    if (obj instanceof Map) {
        return reflectionHashCode((Map) obj);
    }

    // determine whether the object's class declares hashCode() or has a
    // superClass other than java.lang.Object that declares hashCode()
    Class clazz = (obj instanceof Class) ? (Class) obj : obj.getClass();
    Method hashCodeMethod = ReflectionUtils.findMethod(clazz, "hashCode", new Class[0]);

    if (hashCodeMethod != null) {
        return obj.hashCode();
    }

    // could not find a hashCode other than the one declared by java.lang.Object
    int hash = INITIAL_HASH;

    try {
        while (targetClass != null) {
            Field[] fields = targetClass.getDeclaredFields();
            AccessibleObject.setAccessible(fields, true);

            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                int modifiers = field.getModifiers();

                if (!Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)) {
                    hash = MULTIPLIER * hash + reflectionHashCode(field.get(obj));
                }
            }
            targetClass = targetClass.getSuperclass();
        }
    } catch (IllegalAccessException exception) {
        // ///CLOVER:OFF
        ReflectionUtils.handleReflectionException(exception);
        // ///CLOVER:ON
    }

    return hash;
}

From source file:com.blackbear.flatworm.ParseUtils.java

/**
 * Attempt to determine the {@link CardinalityMode} based upon the {@code fieldType}. {@code Collection} based classes
 * and {@code Arrays} will return {@code CardinalityMode.LOOSE} - everything else will return {@code CardinalityMode.SINGLE}.
 * @param fieldType The field type to evaluate.
 * @return {@code CardinalityMode.LOOSE} when the {@code fieldType} is a implementation of a {@link Collection} interface or if
 * {@code fieldType} is an {@code Array}. {@code CardinalityMode.SINGLE} will be returned for all other cases.
 *//*w  ww  . j  a v  a 2 s.  co  m*/
public static CardinalityMode resolveCardinality(Class<?> fieldType) {
    CardinalityMode mode = CardinalityMode.SINGLE;

    if (fieldType != null && (Collection.class.isAssignableFrom(fieldType) || fieldType.isArray())) {
        mode = CardinalityMode.LOOSE;
    }

    return mode;
}

From source file:gdt.data.entity.BaseHandler.java

private static String resolveName(String name, Class c) {
    if (name == null) {
        return name;
    }//from  w  w w.  j  a v  a 2  s. c o m
    if (!name.startsWith("/")) {
        while (c.isArray()) {
            c = c.getComponentType();
        }
        String baseName = c.getName();
        int index = baseName.lastIndexOf('.');
        if (index != -1) {
            name = baseName.substring(0, index).replace('.', '/') + "/" + name;
        }
    } else {
        name = name.substring(1);
    }
    return name;
}