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:io.konik.utils.RandomInvoiceGenerator.java

public Object populteData(Class<?> root, String name) throws InstantiationException, IllegalAccessException,
        NoSuchMethodException, InvocationTargetException {
    Object rootObj;//from  w w  w  . jav  a 2 s  .  com
    if (isLeafType(root)) {//final type
        return generatePrimitveValue(root, name);
    }
    rootObj = createNewInstance(root);

    // get method and populate each of them
    Method[] methods = root.getMethods();
    for (Method method : methods) {
        int methodModifiers = method.getModifiers();
        Class<?> methodParameter = null;
        if (Modifier.isAbstract(methodModifiers) || method.isSynthetic())
            continue;
        if (method.getName().startsWith("add")) {
            methodParameter = method.getParameterTypes()[0];
            if (methodParameter != null && !methodParameter.isArray()
                    && (methodParameter.isInterface() || Modifier.isAbstract(methodParameter.getModifiers()))) {
                continue;
            }
        }
        //getter
        else if (method.getName().startsWith("get")
                && !Collection.class.isAssignableFrom(method.getReturnType())
                && !method.getName().equals("getClass") && !Modifier.isAbstract(methodModifiers)) {
            methodParameter = method.getReturnType();
        } else {
            continue;// next on setter
        }
        if (methodParameter == null || methodParameter.isInterface()) {
            continue;
        }
        Object popultedData = populteData(methodParameter, method.getName());
        setValue(rootObj, method, popultedData);
    }
    return rootObj;
}

From source file:io.neba.core.resourcemodels.metadata.MappedFieldMetaData.java

/**
 * Determines whether the {@link java.lang.reflect.Field#getType() field type}
 * can only be represented by a property of a {@link org.apache.sling.api.resource.Resource},
 * not a {@link org.apache.sling.api.resource.Resource} itself.
 *//*from   w  w w. ja  va 2  s .c  o  m*/
private boolean isPropertyTypeInternal() {
    Class<?> type = getType();
    return
    // References are always contained in properties of type String or String[].
    isReference() || isPropertyType(type)
            || (type.isArray() || isCollectionType) && isPropertyType(getTypeParameter());
}

From source file:com.github.mybatis.spring.MapperFactoryBean.java

protected Object findDefault(Method method) {
    Class<?> clz = method.getReturnType();
    if (clz == String.class) {
        return "";
    } else if (clz == Long.class || clz == Double.class) {
        return 0L;
    } else if (clz == Boolean.class) {
        return Boolean.FALSE;
    } else if (clz.isArray()) {
        return new byte[0];
    } else if (clz.isAssignableFrom(Set.class)) {
        return ImmutableSet.of();
    } else if (clz.isAssignableFrom(List.class)) {
        return ImmutableList.of();
    } else if (clz.isAssignableFrom(Map.class)) {
        return ImmutableMap.of();
    } else {/*ww  w.jav a2s.  c  o m*/
        return null;
    }
}

From source file:com.wfreitas.camelsoap.SoapClient.java

private int calculateCollectionSize(String ognl, Map params) {
    // Try for an Object graph based collection...
    Object param = OGNLUtils.getParameter(ognl, params);
    if (param != null) {
        Class paramRuntime = param.getClass();
        if (paramRuntime.isArray()) {
            return ((Object[]) param).length;
        } else if (Collection.class.isAssignableFrom(paramRuntime)) {
            return ((Collection) param).size();
        }//  ww w . j av a  2 s.c  om
    }

    // Try for <String, Object> collection based map entries...
    Set<Map.Entry> entries = params.entrySet();
    String collectionPrefix = ognl + "[";
    int maxIndex = -1;
    for (Map.Entry entry : entries) {
        Object keyObj = entry.getKey();
        if (keyObj instanceof String) {
            String key = (String) keyObj;
            if (key.startsWith(collectionPrefix)) {
                int endIndex = key.indexOf(']', collectionPrefix.length());
                String ognlIndexValString = key.substring(collectionPrefix.length(), endIndex);
                try {
                    int ognlIndexVal = Integer.valueOf(ognlIndexValString);
                    maxIndex = Math.max(maxIndex, ognlIndexVal);
                } catch (NumberFormatException e) {
                }
            }
        }
    }

    if (maxIndex != -1) {
        return maxIndex + 1;
    }

    // It's a collection, but nothing in this message for it collection...
    return -1;
}

From source file:com.trafficspaces.api.model.Resource.java

public JSONObject getJSONObject() {
    JSONObject jsonObject = new JSONObject();
    Field[] fields = this.getClass().getFields();
    try {/*from  w  w w  . j  av a  2  s . co m*/
        for (int i = 0; i < fields.length; i++) {

            Object fieldValue = fields[i].get(this);
            int fieldModifiers = fields[i].getModifiers();
            //System.out.println("name=" + fields[i].getName() + ", value=" + fieldValue + ", type=" +fields[i].getType() + 
            //      ", ispublic="+Modifier.isPublic(fieldModifiers) + ", isstatic="+Modifier.isStatic(fieldModifiers) + ", isnative="+Modifier.isNative(fieldModifiers));
            if (fieldValue != null && Modifier.isPublic(fieldModifiers) && !Modifier.isStatic(fieldModifiers)
                    && !Modifier.isNative(fieldModifiers)) {

                String name = fields[i].getName();
                Class type = fields[i].getType();

                if (type.isPrimitive()) {
                    if (type.equals(int.class)) {
                        jsonObject.put(name, fields[i].getInt(this));
                    } else if (type.equals(double.class)) {
                        jsonObject.put(name, fields[i].getDouble(this));
                    }
                } else if (type.isArray()) {
                    JSONObject jsonSubObject = new JSONObject();
                    JSONArray jsonArray = new JSONArray();

                    jsonObject.put(name, jsonSubObject);
                    jsonSubObject.put(name.substring(0, name.length() - 1), jsonArray);

                    Object[] values = (Object[]) fieldValue;
                    for (int j = 0; j < values.length; j++) {
                        if (values[j] != null && values[j] instanceof Resource) {
                            jsonArray.put(((Resource) values[j]).getJSONObject());
                        }
                    }
                } else if (Resource.class.isAssignableFrom(type)) {
                    jsonObject.put(name, ((Resource) fieldValue).getJSONObject());
                } else if (type.equals(String.class) && fieldValue != null) {
                    jsonObject.put(name, String.valueOf(fieldValue));
                }
            }
        }
    } catch (Exception nsfe) {
        //
    }
    return jsonObject;
}

From source file:de.interseroh.report.controller.ParameterFormBinder.java

private MutablePropertyValues createPropertyValues(ParameterForm parameterForm,
        final MultiValueMap<String, String> requestParameters) {
    final MutablePropertyValues mpvs = new MutablePropertyValues();

    parameterForm.accept(new AbstractParameterVisitor() {
        @Override/*from  ww w  .  j a v  a2s.  com*/
        public <V, T> void visit(ScalarParameter<V, T> parameter) {
            String name = parameter.getName();
            String propertyPath = ParameterUtils.nameToTextPath(name);
            Class<T> textType = parameter.getTextType();

            if (requestParameters.containsKey(name)) {
                addText(name, propertyPath, textType);
            } else if (requestParameters.containsKey('_' + name)) {
                addText('_' + name, propertyPath, textType);
            }
        }

        private <T> void addText(String name, String propertyPath, Class<T> textType) {
            List<String> values = requestParameters.get(name);
            if (textType.isArray()) {
                mpvs.add(propertyPath, values.toArray());
            } else {
                for (String requestValue : values) {
                    mpvs.add(propertyPath, requestValue);
                }
            }
        }
    });
    return mpvs;
}

From source file:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * Validate a Method to be a main command line application method.
 *
 * Methods with more than 1 argument are not allowed. Methods with return types
 * are not allowed. Methods that throw an exception other than
 * org.apache.commons.cli.CommandLineException are not allowed,
 *
 * @param method the method to validate//from w ww  .j  a  v a  2  s  . co  m
 * @return A new method helper for the method
 */
private CommandLineMethodHelper getHelperForCommandLineMain(Method method) throws CommandLineException {

    // Validate that the return type is a void
    if (!method.getReturnType().equals(Void.TYPE)) {
        throw new CommandLineException("For method " + method.getName() + ", the return type is not void");
    }

    // Validate the exceptions throws by the method
    for (Class<?> clazz : method.getExceptionTypes()) {
        if (!clazz.equals(CommandLineException.class)) {
            throw new CommandLineException("For method " + method.getName()
                    + ", there is an invalid exception class " + clazz.getName());
        }
    }

    // In order to get ready to create the configuration instance,
    // we will need to know the command line option type
    // and the element type.
    Class<?> elementClass;
    MethodType methodType;
    Converter converter;

    // Get the parameters of the method. We'll use these to
    // determine what type of option we have - scalar, boolean, etc.
    Class<?> parameterClasses[] = method.getParameterTypes();

    // See what the length tells us
    switch (parameterClasses.length) {
    case 0:
        throw new CommandLineException("Main command line method must take arguments");
    case 1: {

        // For a method with one argument, we have to look
        // more closely at the argument. It has to be a simple
        // scalar object, an array, or a list.
        Class<?> parameterClass = parameterClasses[0];
        if (parameterClass.isArray()) {

            // For an array, we get the element class based on the
            // underlying component type
            methodType = MethodType.Array;
            elementClass = parameterClass.getComponentType();
        } else {

            // For a scalar, we get the element type from the
            // type of the parameter.
            methodType = MethodType.Scalar;
            elementClass = parameterClass.getClass();
        }

        // Now that we have the element type, make sure it's convertable
        converter = ConvertUtils.lookup(String.class, elementClass);
        if (converter == null) {
            throw new CommandLineException("Cannot find a conversion from String to " + elementClass.getName()
                    + " for method " + method.getName());
        }
        break;
    }
    default: {

        // Other method types not allowed.
        throw new CommandLineException("Method " + method.getName() + " has too many arguments");
    }
    }

    // Now we can return the configuration for this method
    return new CommandLineMethodHelper(method, methodType, elementClass, converter);
}

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

private Class getClassFromHint(Object o) throws UnmarshallException {
    if (o == null)
        return null;
    if (o instanceof JSONObject) {
        try {//from w w w. j a va 2 s.  com
            String class_name = ((JSONObject) o).getString("javaClass");
            Class clazz = Class.forName(class_name);
            return clazz;
        } catch (NoSuchElementException e) {
        } catch (Exception e) {
            throw new UnmarshallException("class in hint not found");
        }
    }
    if (o instanceof JSONArray) {
        JSONArray arr = (JSONArray) o;
        if (arr.length() == 0)
            throw new UnmarshallException("no type for empty array");
        // return type of first element
        Class compClazz = null;
        try {
            compClazz = getClassFromHint(arr.get(0));
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            if (compClazz.isArray())
                return Class.forName("[" + compClazz.getName());
            else
                return Class.forName("[L" + compClazz.getName() + ";");
        } catch (ClassNotFoundException e) {
            throw new UnmarshallException("problem getting array type");
        }
    }
    return o.getClass();
}

From source file:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * Validate a Method to be a command line option methods.
 *
 * Methods with more than 1 argument are not allowed. Methods with return types
 * other than boolean are not allowed. Methods that throw an exception other than
 * org.apache.commons.cli.CommandLineException are not allowed,
 *
 * @param method the method to validate/*from  w  w  w . j  a  va  2s .  c om*/
 * @param commandLineOption the options on that method
 * @return A new method helper for the method
 */
private CommandLineMethodHelper getHelperForCommandOption(Method method, CommandLineOption commandLineOption)
        throws CommandLineException {

    // Validate that the return type is a boolean or void
    if (!method.getReturnType().equals(Boolean.TYPE) && !method.getReturnType().equals(Void.TYPE)) {
        throw new CommandLineException(
                "For method " + method.getName() + ", the return type is not boolean or void");
    }

    // Validate the exceptions throws by the method
    for (Class<?> clazz : method.getExceptionTypes()) {
        if (!clazz.equals(CommandLineException.class)) {
            throw new CommandLineException("For method " + method.getName()
                    + ", there is an invalid exception class " + clazz.getName());
        }
    }

    // In order to get ready to create the configuration instance,
    // we will need to know the command line option type
    // and the element type.
    Class<?> elementClass = null;
    MethodType methodType;
    Converter converter;

    // Get the parameters of the method. We'll use these to
    // determine what type of option we have - scalar, boolean, etc.
    Class<?> parameterClasses[] = method.getParameterTypes();

    // See what the length tells us
    switch (parameterClasses.length) {
    case 0:
        methodType = MethodType.Boolean;
        converter = null;
        break;
    case 1: {

        // For a method with one argument, we have to look
        // more closely at the argument. It has to be a simple
        // scalar object, an array, or a list.
        Class<?> parameterClass = parameterClasses[0];
        if (parameterClass.isArray()) {

            // For an array, we get the element class based on the
            // underlying component type
            methodType = MethodType.Array;
            elementClass = parameterClass.getComponentType();
        } else if (List.class.isAssignableFrom(parameterClass)) {

            // For a list, we get the element class from the command
            // line options annotation
            methodType = MethodType.List;
            elementClass = commandLineOption.argumentType();
        } else {

            // For a scalar, we get the element type from the
            // type of the parameter.
            methodType = MethodType.Scalar;
            elementClass = parameterClass.getClass();
        }

        // Now that we have the element type, make sure it's convertable
        converter = ConvertUtils.lookup(String.class, elementClass);
        if (converter == null) {
            throw new CommandLineException("Cannot find a conversion from String to " + elementClass.getName()
                    + " for method " + method.getName());
        }
        break;
    }
    default: {

        // Other method types not allowed.
        throw new CommandLineException("Method " + method.getName() + " has too many arguments");
    }
    }

    // Now we can return the configuration for this method
    return new CommandLineMethodHelper(method, methodType, elementClass, converter);
}

From source file:com.comcast.cereal.engines.AbstractCerealEngine.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> T deCerealize(Object cereal, Class<T> clazz) throws CerealException {
    ObjectCache objectCache = new ObjectCache(settings);
    try {//from  w ww.  ja v  a2  s .co m
        if (cereal instanceof List && clazz.isArray()) {
            List<Object> cerealList = (List) cereal;
            Class arrayType = clazz.getComponentType();
            Cerealizer cerealizer = cerealFactory.getCerealizer(arrayType);

            T array = (T) Array.newInstance(arrayType, cerealList.size());
            for (int i = 0; i < cerealList.size(); i++) {
                Array.set(array, i, cerealizer.deCerealize(cerealList.get(i), objectCache));
            }

            return array;
        } else {
            Class<?> runtimeClass = cerealFactory.getRuntimeClass(cereal);
            Cerealizer cerealizer = cerealFactory.getCerealizer(clazz);

            if ((runtimeClass != null) && clazz.isAssignableFrom(runtimeClass)) {
                /** need to check if the runtime class is a subclass of the given class
                 *  or we will get a class cast exception when we return it */
                cerealizer = cerealFactory.getRuntimeCerealizer(cereal, cerealizer);
            }
            return (T) cerealizer.deCerealize(cereal, objectCache);
        }
    } finally {
        objectCache.resetCache();
    }
}