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:org.apache.ode.il.DynamicService.java

@SuppressWarnings("unchecked")
private static Object convertFromOM(Class<?> clazz, OMElement elmt) {
    // Here comes the nasty code...
    if (elmt == null || elmt.getText().length() == 0 && !elmt.getChildElements().hasNext())
        return null;
    else if (clazz.equals(String.class)) {
        return elmt.getText();
    } else if (clazz.equals(Boolean.class) || clazz.equals(Boolean.TYPE)) {
        return (elmt.getText().equals("true") || elmt.getText().equals("yes")) ? Boolean.TRUE : Boolean.FALSE;
    } else if (clazz.equals(QName.class)) {
        // The getTextAsQName is buggy, it sometimes return the full text without extracting namespace
        return OMUtils.getTextAsQName(elmt);
    } else if (clazz.equals(ProcessInfoCustomizer.class)) {
        return new ProcessInfoCustomizer(elmt.getText());
    } else if (Node.class.isAssignableFrom(clazz)) {
        return OMUtils.toDOM(elmt.getFirstElement());
    } else if (clazz.equals(Long.TYPE) || clazz.equals(Long.class)) {
        return Long.parseLong(elmt.getText());
    } else if (clazz.equals(Integer.TYPE) || clazz.equals(Integer.class)) {
        return Integer.parseInt(elmt.getText());
    } else if (clazz.isArray()) {
        ArrayList<Object> alist = new ArrayList<Object>();
        Iterator<OMElement> children = elmt.getChildElements();
        Class<?> targetClazz = clazz.getComponentType();
        while (children.hasNext())
            alist.add(parseType(targetClazz, ((OMElement) children.next()).getText()));
        return alist.toArray((Object[]) Array.newInstance(targetClazz, alist.size()));
    } else if (XmlObject.class.isAssignableFrom(clazz)) {
        try {/*from   ww  w .  j  av  a 2s . c  o m*/
            Class beanFactory = clazz.forName(clazz.getCanonicalName() + "$Factory");
            elmt.setNamespace(elmt.declareDefaultNamespace(""));
            elmt.setLocalName("xml-fragment");
            return beanFactory.getMethod("parse", XMLStreamReader.class).invoke(null,
                    elmt.getXMLStreamReaderWithoutCaching());
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(
                    "Couldn't find class " + clazz.getCanonicalName() + ".Factory to instantiate xml bean", e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(
                    "Couldn't access class " + clazz.getCanonicalName() + ".Factory to instantiate xml bean",
                    e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("Couldn't access xml bean parse method on class "
                    + clazz.getCanonicalName() + ".Factory " + "to instantiate xml bean", e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Couldn't find xml bean parse method on class "
                    + clazz.getCanonicalName() + ".Factory " + "to instantiate xml bean", e);
        }
    } else
        throw new RuntimeException(
                "Couldn't use element " + elmt + " to obtain a management method parameter.");
}

From source file:com.link_intersystems.lang.reflect.Member2.java

private Object createVarargsArray(Parameter varargsParameter, int varargsParamIndex, Object[] callParameters) {
    Class2<?> parameterClass2 = varargsParameter.getParameterClass2();
    Class<?> type = parameterClass2.getType();
    Class<?> componentType = type.getComponentType();
    Object varargsArray = Array.newInstance(type.getComponentType(), callParameters.length - varargsParamIndex);
    if (componentType.isPrimitive()) {
        PrimitiveArrayCallback primitiveCallback = new PrimitiveArrayCallback(varargsArray);
        for (int varargsIndex = varargsParamIndex; varargsIndex < callParameters.length; varargsIndex++) {
            Object object = callParameters[varargsIndex];
            Conversions.unbox(object, primitiveCallback);
        }//from w  ww . j  av a2 s. c o m
    } else {
        System.arraycopy(callParameters, varargsParamIndex, varargsArray, 0, Array.getLength(varargsArray));
    }
    return varargsArray;
}

From source file:org.apache.cxf.jaxbplus.io.DataWriterImpl.java

public Marshaller createMarshaller(Object elValue, MessagePartInfo part) {
    Class<?> cls = null;
    if (part != null) {
        cls = part.getTypeClass();//from w  w w .  j  a  v a2 s  .c om
    }

    if (cls == null) {
        cls = null != elValue ? elValue.getClass() : null;
    }

    if (cls != null && cls.isArray() && elValue instanceof Collection) {
        Collection<?> col = (Collection<?>) elValue;
        elValue = col.toArray((Object[]) Array.newInstance(cls.getComponentType(), col.size()));
    }
    Marshaller marshaller;
    try {

        marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
        marshaller.setListener(databinding.getMarshallerListener());
        if (databinding.getValidationEventHandler() != null) {
            marshaller.setEventHandler(databinding.getValidationEventHandler());
        }

        final Map<String, String> nspref = databinding.getDeclaredNamespaceMappings();
        if (nspref != null) {
            JAXBUtils.setNamespaceWrapper(nspref, marshaller);
        }
        if (databinding.getMarshallerProperties() != null) {
            for (Map.Entry<String, Object> propEntry : databinding.getMarshallerProperties().entrySet()) {
                try {
                    marshaller.setProperty(propEntry.getKey(), propEntry.getValue());
                } catch (PropertyException pe) {
                    LOG.log(Level.INFO, "PropertyException setting Marshaller properties", pe);
                }
            }
        }

        marshaller.setSchema(schema);
        AttachmentMarshaller atmarsh = getAttachmentMarshaller();
        marshaller.setAttachmentMarshaller(atmarsh);

        if (schema != null && atmarsh instanceof JAXBAttachmentMarshaller) {
            //we need a special even handler for XOP attachments 
            marshaller.setEventHandler(new MtomValidationHandler(marshaller.getEventHandler(),
                    (JAXBAttachmentMarshaller) atmarsh));
        }
    } catch (JAXBException ex) {
        if (ex instanceof javax.xml.bind.MarshalException) {
            javax.xml.bind.MarshalException marshalEx = (javax.xml.bind.MarshalException) ex;
            Message faultMessage = new Message("MARSHAL_ERROR", LOG,
                    marshalEx.getLinkedException().getMessage());
            throw new Fault(faultMessage, ex);
        } else {
            throw new Fault(new Message("MARSHAL_ERROR", LOG, ex.getMessage()), ex);
        }
    }
    return marshaller;
}

From source file:org.apache.axis.wsdl.toJava.JavaGeneratorFactory.java

/**  
 * Gets class name from Java class.// w  w w  .  java2  s .  c  o m
 * If the class is an array, get its component type's name
 * @param clazz a java class
 * @return the class name in string
 */
private static String getJavaClassName(Class clazz) {
    Class class1 = clazz;

    while (class1.isArray()) {
        class1 = class1.getComponentType();
    }

    String name = class1.getName();
    name.replace('$', '.');
    return name;
}

From source file:com.angkorteam.framework.swagger.factory.SwaggerFactory.java

public static boolean isModelArray(Class<?> type) {
    return type.isArray() && (type != byte[].class && type != Byte[].class && type != short[].class
            && type != Short[].class && type != int[].class && type != Integer[].class && type != float[].class
            && type != Float[].class && type != long[].class && type != Long[].class && type != double[].class
            && type != Double[].class && type != boolean[].class && type != Boolean[].class
            && type != char[].class && type != Character[].class && type != Date[].class
            && type != MultipartFile[].class && type != String[].class
            && type.getComponentType().getAnnotation(ApiModel.class) != null);
}

From source file:org.enerj.apache.commons.beanutils.ConvertUtilsBean.java

/**
 * Convert an array of specified values to an array of objects of the
 * specified class (if possible).  If the specified Java class is itself
 * an array class, this class will be the type of the returned value.
 * Otherwise, an array will be constructed whose component type is the
 * specified class./*from  w ww .j  av a 2  s  .com*/
 *
 * @param values Values to be converted (may be null)
 * @param clazz Java array or element class to be converted to
 *
 * @exception ConversionException if thrown by an underlying Converter
 */
public Object convert(String values[], Class clazz) {

    Class type = clazz;
    if (clazz.isArray()) {
        type = clazz.getComponentType();
    }
    if (log.isDebugEnabled()) {
        log.debug("Convert String[" + values.length + "] to class '" + type.getName() + "[]'");
    }
    Converter converter = lookup(type);
    if (converter == null) {
        converter = lookup(String.class);
    }
    if (log.isTraceEnabled()) {
        log.trace("  Using converter " + converter);
    }
    Object array = Array.newInstance(type, values.length);
    for (int i = 0; i < values.length; i++) {
        Array.set(array, i, converter.convert(type, values[i]));
    }
    return (array);

}

From source file:com.medallia.spider.api.DynamicInputImpl.java

/**
 * @param rt some kind of array class/*from  w  w  w .j  av  a2 s. c o  m*/
 * @param data null, String or String[]
 * @return parsed data as per parseSingleValue
 * @throws AssertionError if parseSingleValue does
 */
private Object parseMultiValue(Class<?> rt, Object data, AnnotatedElement anno) throws AssertionError {
    String[] xs;
    // normalize the zero-and-one cases
    if (data == null) {
        xs = new String[0];
    } else if (data instanceof String[]) {
        xs = (String[]) data;
    } else {
        xs = new String[] { data.toString() };
    }

    Class<?> comp = rt.getComponentType();
    Object arr = Array.newInstance(rt.getComponentType(), xs.length);
    for (int i = 0; i < xs.length; i++) {
        Array.set(arr, i, parseSingleValue(comp, xs[i], anno, inputArgParsers));
    }
    return arr;
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private Object doConvertToArray(Map<String, Object> context, Object o, Member member, String s, Object value,
        Class toType) {
    Object result = null;/*from   w w  w  .j a  v a 2  s.c  o m*/
    Class componentType = toType.getComponentType();

    if (componentType != null) {
        TypeConverter converter = getTypeConverter(context);

        if (value.getClass().isArray()) {
            int length = Array.getLength(value);
            result = Array.newInstance(componentType, length);

            for (int i = 0; i < length; i++) {
                Object valueItem = Array.get(value, i);
                Array.set(result, i, converter.convertValue(context, o, member, s, valueItem, componentType));
            }
        } else {
            result = Array.newInstance(componentType, 1);
            Array.set(result, 0, converter.convertValue(context, o, member, s, value, componentType));
        }
    }

    return result;
}

From source file:com.google.flatbuffers.Table.java

@SuppressWarnings("unchecked")
@Override/*from www  .  ja  v a2  s  . c o  m*/
public int clone(FlatBufferBuilder builder, Map<String, Object> mutate) throws Exception {
    int root_table = -1;
    Class<?> cls = this.getClass();
    HashMap<String, Object> v = new HashMap<String, Object>();
    try {
        //b0. phan loai method
        List<Method> msAdd = new ArrayList<Method>();
        List<Method> msGet = new ArrayList<Method>();
        HashMap<String, Method> msCreateVector = new HashMap<String, Method>();
        Method[] ms = this.getClass().getDeclaredMethods();
        for (Method m : ms) {
            String sMethodName = m.getName();
            if (m.getParameterTypes().length == 0 && !sMethodName.endsWith("AsByteBuffer"))
                msGet.add(m);
            else if (m.getParameterTypes().length == 2 && sMethodName.startsWith("add"))
                msAdd.add(m);
            else if (m.getParameterTypes().length == 2 && sMethodName.startsWith("create")
                    && sMethodName.endsWith("Vector"))
                msCreateVector.put(sMethodName, m);
        }
        //b1. lay ds thuoc tinh va gia tri
        for (Method m : msGet) {
            String sMethodName = m.getName();
            if (sMethodName.endsWith("Length")) {
                int ii = sMethodName.lastIndexOf("Length");
                String sMethodName1 = sMethodName.substring(0, ii);
                int iLength = 0;
                try {
                    iLength = (int) m.invoke(this, new Object[] {});
                } catch (Exception e) {
                }
                List<Object> l = new ArrayList<>();
                for (int i = 0; i < iLength; i++) {
                    Method m1 = this.getClass().getDeclaredMethod(sMethodName1,
                            new Class<?>[] { Integer.TYPE });
                    Object oKq = m1.invoke(this, new Object[] { i });
                    l.add(oKq);
                }
                v.put(sMethodName1, l);
            } else {
                Object oKq = m.invoke(this, new Object[] {});
                v.put(sMethodName, oKq);
            }
        }
        //b2. khoi tao gia tri cho builder
        for (Entry<String, Object> e : v.entrySet()) {
            String sKey = e.getKey();
            Object oValue = e.getValue();
            Object oNewValue = mutate != null ? mutate.get(sKey) : null;
            if (oValue instanceof String || oNewValue instanceof String) {
                int keyOffset = builder
                        .createString(oNewValue == null ? oValue.toString() : oNewValue.toString());
                v.put(sKey, keyOffset);
            } else if (oValue instanceof List || oNewValue instanceof List) {
                List<?> oV = (List<?>) (oNewValue == null ? oValue : oNewValue);
                int iLen = ((List<?>) oV).size();
                if (iLen <= 0)
                    v.put(sKey, null);
                else {
                    Object obj = ((List<?>) oV).get(0);
                    if (obj instanceof Table || obj instanceof Struct) {
                        int[] keyOffsetList = new int[iLen];
                        boolean isHasValue = false;
                        for (int i = 0; i < iLen; i++) {
                            obj = ((List<?>) oV).get(i);
                            int offset = ((IFlatBuffer) obj).clone(builder, null);
                            if (offset != -1) {
                                keyOffsetList[i] = offset;
                                isHasValue = true;
                            }
                        }
                        if (isHasValue) {
                            int keyOffset = -1;
                            Method m = cls.getDeclaredMethod("create" + WordUtils.capitalize(sKey) + "Vector",
                                    new Class<?>[] { FlatBufferBuilder.class, int[].class });
                            keyOffset = (int) m.invoke(null, new Object[] { builder, keyOffsetList });
                            if (keyOffset != -1)
                                v.put(sKey, keyOffset);
                        }
                    } else if (obj instanceof String) {
                        int[] keyOffsetList = new int[iLen];
                        boolean isHasValue = false;
                        for (int i = 0; i < iLen; i++) {
                            obj = ((List<String>) oV).get(i);
                            int offset = builder.createString((CharSequence) obj);
                            if (offset != -1) {
                                keyOffsetList[i] = offset;
                                isHasValue = true;
                            }
                        }
                        if (isHasValue) {
                            int keyOffset = -1;
                            Method m = cls.getDeclaredMethod("create" + WordUtils.capitalize(sKey) + "Vector",
                                    new Class<?>[] { FlatBufferBuilder.class, int[].class });
                            keyOffset = (int) m.invoke(null, new Object[] { builder, keyOffsetList });
                            if (keyOffset != -1)
                                v.put(sKey, keyOffset);
                        }
                    } else {
                        int keyOffset = -1;
                        Method m = msCreateVector.get("create" + WordUtils.capitalize(sKey) + "Vector");
                        Class<?> subCls = Class.forName(m.getParameterTypes()[1].getName());
                        Class<?> objType = subCls.getComponentType();
                        String objTypeName = objType.getSimpleName();
                        Method mo = Number.class.getDeclaredMethod(objTypeName + "Value", new Class<?>[] {});
                        Object aObject = Array.newInstance(objType, iLen);
                        for (int i = 0; i < iLen; i++)
                            Array.set(aObject, i, mo.invoke(((List<Number>) oV).get(i), new Object[] {}));
                        keyOffset = (int) m.invoke(null, new Object[] { builder, aObject });
                        if (keyOffset != -1)
                            v.put(sKey, keyOffset);
                    }
                }
            } else if (oValue instanceof Table || oValue instanceof Struct || oNewValue instanceof Table
                    || oNewValue instanceof Struct) {
                int keyOffset = -1;
                if (oNewValue != null)
                    keyOffset = ((IFlatBuffer) oNewValue).clone(builder, mutate);
                else
                    keyOffset = ((IFlatBuffer) oValue).clone(builder, mutate);
                if (keyOffset != -1)
                    v.put(sKey, keyOffset);
            } else {
                if (oNewValue != null)
                    v.put(sKey, oNewValue);
            }
        }
        //b3. gan gia tri cho clone object
        Method m = cls.getDeclaredMethod("start" + cls.getSimpleName(),
                new Class<?>[] { FlatBufferBuilder.class });
        m.invoke(null, new Object[] { builder });
        for (Method mAdd : msAdd) {
            String sFieldName = mAdd.getName().replace("add", "");
            sFieldName = WordUtils.uncapitalize(sFieldName);
            Object oFieldValue = v.get(sFieldName);
            if (oFieldValue != null && !(oFieldValue instanceof Table || oFieldValue instanceof Struct)) {
                mAdd.invoke(null, new Object[] { builder, oFieldValue });
            }
        }
        m = cls.getDeclaredMethod("end" + cls.getSimpleName(), new Class<?>[] { FlatBufferBuilder.class });
        root_table = (int) m.invoke(null, new Object[] { builder });
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return root_table;
}