Example usage for java.lang Class getComponentType

List of usage examples for java.lang Class getComponentType

Introduction

In this page you can find the example usage for java.lang Class getComponentType.

Prototype

public Class<?> getComponentType() 

Source Link

Document

Returns the Class representing the component type of an array.

Usage

From source file:com.github.helenusdriver.driver.impl.DataDecoder.java

/**
 * Gets an element decoder that can be used to convert a Cassandra
 * returned data type into another data type based on special supported
 * combinations.//w ww .  j ava  2 s . c om
 *
 * @author paouelle
 *
 * @param  eclass the non-<code>null</code> element class to decode to
 * @param  reclass the non-<code>null</code> row's element class
 * @return a non-<code>null</code> element decoder for the provided combination
 * @throws IllegalArgumentException if the combination is not supported
 */
@SuppressWarnings("rawtypes")
static ElementConverter getConverter(final Class eclass, Class reclass) {
    if (Enum.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @SuppressWarnings("unchecked")
            @Override
            public Object convert(Object re) {
                return Enum.valueOf(eclass, (String) re);
            }
        };
    } else if (Locale.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return LocaleUtils.toLocale((String) re);
            }
        };
    } else if (ZoneId.class.isAssignableFrom(eclass) && (String.class == reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                try {
                    return ZoneId.of((String) re);
                } catch (DateTimeException e) {
                    throw new IllegalArgumentException(e);
                }
            }
        };
    } else if (eclass.isArray() && (Byte.TYPE == eclass.getComponentType())
            && ByteBuffer.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return Bytes.getArray((ByteBuffer) re);
            }
        };
    } else if ((Long.class == eclass) && Date.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return ((Date) re).getTime();
            }
        };
    } else if ((Instant.class == eclass) && Date.class.isAssignableFrom(reclass)) {
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return ((Date) re).toInstant();
            }
        };
    } else if (eclass == reclass) { // special case for maps
        return new ElementConverter() {
            @Override
            public Object convert(Object re) {
                return re;
            }
        };
    }
    throw new IllegalArgumentException(
            "unsupported element conversion from: " + reclass.getName() + " to: " + eclass.getName());
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

/**
 * Returns the literal value of an object that is suitable for inclusion in Java Source code.
 *
 * <p>//w  ww .  ja v a 2 s  .  c o m
 * Supports all types that {@link Annotation} value can have.
 * </p>
 *
 *
 * @throws IllegalArgumentException if the type of the object does not have a java literal form.
 */
public static String asLiteral(final Object value) throws IllegalArgumentException {
    final Class<?> clazz = value.getClass();

    if (clazz.isArray()) {
        final StringBuilder sb = new StringBuilder();
        final Object[] array = (Object[]) value;

        sb.append("new " + clazz.getComponentType().getCanonicalName() + "[] {");
        boolean first = true;
        for (final Object object : array) {
            if (first) {
                first = false;
            } else {
                sb.append(',');
            }
            sb.append(asLiteral(object));
        }
        sb.append('}');
        return sb.toString();
    }

    if (value instanceof Boolean) {
        return JBooleanLiteral.get(((Boolean) value).booleanValue()).toSource();
    } else if (value instanceof Byte) {
        return JIntLiteral.get(((Byte) value).byteValue()).toSource();
    } else if (value instanceof Character) {
        return JCharLiteral.get(((Character) value).charValue()).toSource();
    } else if (value instanceof Class<?>) {
        return ((Class<?>) (Class<?>) value).getCanonicalName() + ".class";
    } else if (value instanceof Double) {
        return JDoubleLiteral.get(((Double) value).doubleValue()).toSource();
    } else if (value instanceof Enum) {
        return value.getClass().getCanonicalName() + "." + ((Enum<?>) value).name();
    } else if (value instanceof Float) {
        return JFloatLiteral.get(((Float) value).floatValue()).toSource();
    } else if (value instanceof Integer) {
        return JIntLiteral.get(((Integer) value).intValue()).toSource();
    } else if (value instanceof Long) {
        return JLongLiteral.get(((Long) value).longValue()).toSource();
    } else if (value instanceof String) {
        return '"' + Generator.escape((String) value) + '"';
    } else {
        // TODO(nchalko) handle Annotation types
        throw new IllegalArgumentException(value.getClass() + " can not be represented as a Java Literal.");
    }
}

From source file:coria2015.server.JsonRPCMethods.java

private int convert(Object p, Arguments description, int score, Object args[], int index) {
        Object o;//from  w ww . j  a  va  2 s . c o  m
        if (p instanceof JSONObject)
            // If p is a map, then use the json name of the argument
            o = ((JSONObject) p).get(description.getArgument(index).name());

        else if (p instanceof JSONArray)
            // if it is an array, then map it
            o = ((JSONArray) p).get(index);
        else {
            // otherwise, suppose it is a one value array
            if (index > 0)
                return Integer.MIN_VALUE;
            o = p;
        }

        final Class aType = description.getType(index);

        if (o == null) {
            if (description.getArgument(index).required())
                return Integer.MIN_VALUE;

            return score - 10;
        }

        if (aType.isArray()) {
            if (o instanceof JSONArray) {
                final JSONArray array = (JSONArray) o;
                final Object[] arrayObjects = args != null ? new Object[array.size()] : null;
                Arguments arguments = new Arguments() {
                    @Override
                    public RPCArgument getArgument(int i) {
                        return new RPCArrayArgument();
                    }

                    @Override
                    public Class<?> getType(int i) {
                        return aType.getComponentType();
                    }

                    @Override
                    public int size() {
                        return array.size();
                    }
                };
                for (int i = 0; i < array.size() && score > Integer.MIN_VALUE; i++) {
                    score = convert(array.get(i), arguments, score, arrayObjects, i);
                }
                return score;
            }
            return Integer.MIN_VALUE;
        }

        if (aType.isAssignableFrom(o.getClass())) {
            if (args != null)
                args[index] = o;
            return score;
        }

        if (o.getClass() == Long.class && aType == Integer.class) {
            if (args != null)
                args[index] = ((Long) o).intValue();
            return score - 1;
        }

        return Integer.MIN_VALUE;
    }

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

private Object newValue(Class<?> type, TypeDescriptor desc, String name) {
    try {//from  ww w.java 2 s  .c om
        if (type.isArray()) {
            Class<?> componentType = type.getComponentType();
            // #TO#DO# - only handles 2-dimensional arrays
            if (componentType.isArray()) {
                Object array = Array.newInstance(componentType, 1);
                Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
                return array;
            } else {
                return Array.newInstance(componentType, 0);
            }
        } else if (Collection.class.isAssignableFrom(type)) {
            TypeDescriptor elementDesc = (desc != null ? desc.getElementTypeDescriptor() : null);
            return CollectionFactory.createCollection(type,
                    (elementDesc != null ? elementDesc.getType() : null), 16);
        } else if (Map.class.isAssignableFrom(type)) {
            TypeDescriptor keyDesc = (desc != null ? desc.getMapKeyTypeDescriptor() : null);
            return CollectionFactory.createMap(type, (keyDesc != null ? keyDesc.getType() : null), 16);
        } else {
            return type.newInstance();
        }
    } catch (Exception ex) {
        // #TO#DO#: Root cause exception context is lost here; just exception message preserved.
        // Should we throw another exception type that preserves context instead?
        throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name,
                "Could not instantiate property type [" + type.getName()
                        + "] to auto-grow nested property path: " + ex);
    }
}

From source file:eu.sathra.io.IO.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getValue(JSONObject jObj, String param, Class<?> clazz)
        throws ArrayIndexOutOfBoundsException, IllegalArgumentException, Exception {
    try {//from  w w w. j  av  a  2 s  . c om
        if (clazz.equals(String.class)) {
            return jObj.getString(param);
        } else if (clazz.equals(int.class)) {
            return jObj.getInt(param);
        } else if (clazz.equals(long.class)) {
            return jObj.getLong(param);
        } else if (clazz.equals(float.class)) {
            return (float) jObj.getDouble(param);
        } else if (clazz.equals(double.class)) {
            return jObj.getDouble(param);
        } else if (clazz.equals(boolean.class)) {
            return jObj.getBoolean(param);
        } else if (mAdapters.containsKey(clazz)) {
            return mAdapters.get(clazz).load(param, jObj);
        } else if (clazz.isEnum()) {
            return Enum.valueOf((Class<? extends Enum>) clazz, jObj.getString(param));
        } else if (clazz.isArray()) {
            return getValue(jObj.getJSONArray(param), clazz.getComponentType());
        } else {
            return load(jObj.getJSONObject(param), clazz);
        }
    } catch (JSONException e) {
        return null;
    } finally {
        jObj.remove(param);
    }

}

From source file:org.evosuite.testcarver.testcase.EvoTestCaseCodeGenerator.java

@Override
public void createArrayInitStmt(final CaptureLog log, final int logRecNo) {
    final int oid = log.objectIds.get(logRecNo);

    final Object[] params = log.params.get(logRecNo);
    final String arrTypeName = log.getTypeName(oid);
    final Class<?> arrType = getClassForName(arrTypeName);

    // --- create array instance creation e.g. int[] var = new int[10];

    final ArrayReference arrRef;

    // create array only once
    if (this.oidToVarRefMap.containsKey(oid)) {
        arrRef = (ArrayReference) this.oidToVarRefMap.get(oid);
    } else {//from  ww w  . jav a  2 s . c om
        arrRef = new ArrayReference(testCase, arrType);
        final ArrayStatement arrStmt = new ArrayStatement(testCase, arrRef);
        arrStmt.setSize(params.length);
        testCase.addStatement(arrStmt);
        this.oidToVarRefMap.put(oid, arrRef);
    }

    final Class<?> arrCompClass = arrType.getComponentType();

    AssignmentStatement assignStmt;
    ArrayIndex arrIndex;
    VariableReference valueRef;
    Integer argOID; // is either an oid or null
    for (int i = 0; i < params.length; i++) {
        argOID = (Integer) params[i];
        if (argOID == null) {
            valueRef = testCase.addStatement(new NullStatement(testCase, arrCompClass));
        } else {
            valueRef = this.oidToVarRefMap.get(argOID);
            if (valueRef == null) {
                logger.info("ValueREF is NULL for " + argOID);
                continue;
            }
        }

        arrIndex = new ArrayIndex(testCase, arrRef, i);
        assignStmt = new AssignmentStatement(testCase, arrIndex, valueRef);
        testCase.addStatement(assignStmt);
        logger.debug("Adding assignment (array): " + assignStmt.getCode());
    }
}

From source file:com.seleniumtests.reporter.SeleniumTestsReporter.java

protected String getType(Class<?> cls) {

    while (cls.isArray()) {
        cls = cls.getComponentType();
    }/*from w w  w  . j  a  v  a 2 s.c o m*/

    return cls.getName();
}

From source file:net.sourceforge.vulcan.web.struts.forms.PluginConfigForm.java

@SuppressWarnings("unchecked")
private String getTypeAndPrepare(String propertyName, PropertyDescriptor pd) {
    final Class<?> c = pd.getPropertyType();
    final ConfigChoice choicesType = (ConfigChoice) pd.getValue(PluginConfigDto.ATTR_CHOICE_TYPE);

    if (choicesType != null) {
        switch (choicesType) {
        case PROJECTS:
            choices.put(propertyName, availableProjects);
            break;
        case INLINE:
            choices.put(propertyName, (List<String>) pd.getValue(PluginConfigDto.ATTR_AVAILABLE_CHOICES));
        }/* ww w.  j a v  a 2  s  .  c o m*/
        if (c.isArray()) {
            return "choice-array";
        }
        return "enum";
    }

    final Widget widget = (Widget) pd.getValue(PluginConfigDto.ATTR_WIDGET_TYPE);

    if (Widget.PASSWORD.equals(widget)) {
        hidePassword(propertyName);
    }

    if (c.isArray()) {
        final Class<?> componentType = c.getComponentType();
        if (isPrimitive(componentType)) {
            return "primitive-array";
        } else if (Enum.class.isAssignableFrom(componentType)) {
            populateEnumChoices(propertyName, componentType);
            return "choice-array";
        }
        return "object-array";
    } else if (isBoolean(c)) {
        return "boolean";
    } else if (isPrimitive(c)) {
        if (widget != null) {
            return widget.name().toLowerCase();
        }
        return "primitive";
    } else if (Enum.class.isAssignableFrom(c)) {
        populateEnumChoices(propertyName, c);
        if (widget != null) {
            return widget.name().toLowerCase();
        }
        return "enum";
    }
    return "object";
}

From source file:omero.util.IceMapper.java

/**
 * Supports the separate case of reversing for arrays. See
 * {@link #reverse(Collection, Class)} and {@link #map(Filterable[])}.
 * //  w w  w  .j  av a 2  s .c  o m
 * @param list
 * @param type
 * @return
 * @throws omero.ServerError
 */
public Object[] reverseArray(List list, Class type) throws omero.ServerError {

    if (list == null) {
        return null;
    }

    Class component = type.getComponentType();
    Object[] array = null;
    try {

        array = (Object[]) Array.newInstance(component, list.size());
        for (int i = 0; i < array.length; i++) {
            array[i] = this.handleInput(component, list.get(i));
        }
    } catch (Exception e) {
        String msg = "Cannot create array from type " + type;
        if (log.isErrorEnabled()) {
            log.error(msg, e);
        }
        omero.ApiUsageException aue = new omero.ApiUsageException();
        aue.message = msg;
        aue.serverExceptionClass = e.getClass().getName();
        throw aue;
    }

    return array;
}

From source file:org.apache.bval.jsr.xml.ValidationMappingParser.java

private Object getElementValue(ElementType elementType, Class<?> returnType, String defaultPackage) {
    removeEmptyContentElements(elementType);

    boolean isArray = returnType.isArray();
    if (!isArray) {
        if (elementType.getContent().size() != 1) {
            throw new ValidationException("Attempt to specify an array where single value is expected.");
        }//from w ww . jav a  2 s . com
        return getSingleValue(elementType.getContent().get(0), returnType, defaultPackage);
    }
    List<Object> values = new ArrayList<Object>();
    for (Serializable s : elementType.getContent()) {
        values.add(getSingleValue(s, returnType.getComponentType(), defaultPackage));
    }
    return values.toArray((Object[]) Array.newInstance(returnType.getComponentType(), values.size()));
}