List of usage examples for java.lang Class getComponentType
public Class<?> getComponentType()
From source file:org.eclipse.swt.examples.controlexample.Tab.java
String parameterInfo(String methodRoot) { String typeName = null;//from w w w. jav a 2s. c o m Class<?> returnType = getReturnType(methodRoot); boolean isArray = returnType.isArray(); if (isArray) { typeName = returnType.getComponentType().getName(); } else { typeName = returnType.getName(); } String typeNameString = typeName; int index = typeName.lastIndexOf('.'); if (index != -1 && index + 1 < typeName.length()) typeNameString = typeName.substring(index + 1); String info = ControlExample.getResourceString("Info_" + typeNameString + (isArray ? "A" : "")); if (isArray) { typeNameString += "[]"; } return ControlExample.getResourceString("Parameter_Info", new Object[] { typeNameString, info }); }
From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java
private boolean hasMatchingAnnotation(final Annotation expectedAnnotation, final Annotation[] annotations) throws UnableToCompleteException { // See spec section 2.2. Applying multiple constraints of the same type for (final Annotation annotation : annotations) { // annotations not annotated by @Constraint if (annotation.annotationType().getAnnotation(Constraint.class) == null) { try { // value element has a return type of an array of constraint // annotations final Method valueMethod = annotation.annotationType().getMethod("value"); final Class<?> valueType = valueMethod.getReturnType(); if (valueType.isArray() && Annotation.class.isAssignableFrom(valueType.getComponentType())) { if (Modifier.isAbstract(valueMethod.getModifiers())) { // handle edge case where interface is marked "abstract" valueMethod.setAccessible(true); }//from ww w . jav a2s.c o m final Annotation[] valueAnnotions = (Annotation[]) valueMethod.invoke(annotation); for (final Annotation annotation2 : valueAnnotions) { if (expectedAnnotation.equals(annotation2)) { return true; } } } } catch (final NoSuchMethodException ignore) { // NOPMD // Expected Case. } catch (final Exception e) { throw error(this.logger, e); } } } return false; }
From source file:org.apache.axis.wsdl.fromJava.Types.java
/** * Write a parameter (a sub-element) into a sequence generated by * writeWrapperElement() above./*from www .j av a 2 s . c o m*/ * * @param sequence the <sequence> in which we're writing * @param name is the name of an element to add to the wrapper element. * @param type is the QName of the type of the element. * @param javaType * @throws AxisFault */ public void writeWrappedParameter(Element sequence, String name, QName type, Class javaType) throws AxisFault { if (javaType == void.class) { return; } // JAX-RPC 1.1 says that byte[] should always be a Base64Binary // This (rather strange) hack will ensure that we don't map it // in to an maxoccurs=unbounded array. if (javaType.isArray() && !javaType.equals(byte[].class)) { type = writeTypeForPart(javaType.getComponentType(), null); } else { type = writeTypeForPart(javaType, type); } if (type == null) { // TODO: throw an Exception!! return; } Element childElem; if (isAnonymousType(type)) { childElem = createElementWithAnonymousType(name, javaType, false, docHolder); } else { // Create the child <element> and add it to the wrapper <sequence> childElem = docHolder.createElement("element"); childElem.setAttribute("name", name); String prefix = namespaces.getCreatePrefix(type.getNamespaceURI()); String prefixedName = prefix + ":" + type.getLocalPart(); childElem.setAttribute("type", prefixedName); // JAX-RPC 1.1 says that byte[] should always be a Base64Binary // This (rather strange) hack will ensure that we don't map it // in to an maxoccurs=unbounded array. if (javaType.isArray() && !javaType.equals(byte[].class)) { childElem.setAttribute("maxOccurs", "unbounded"); } } sequence.appendChild(childElem); }
From source file:com.espertech.esper.util.PopulateUtil.java
private static Object coerceProperty(String propertyName, Class containingType, Object value, Class type, EngineImportService engineImportService, boolean forceNumeric) throws ExprValidationException { if (value instanceof ExprNode && type != ExprNode.class) { if (value instanceof ExprIdentNode) { ExprIdentNode identNode = (ExprIdentNode) value; Property prop;/*from w w w . ja v a 2 s.co m*/ try { prop = PropertyParser.parse(identNode.getFullUnresolvedName(), false); } catch (Exception ex) { throw new ExprValidationException( "Failed to parse property '" + identNode.getFullUnresolvedName() + "'"); } if (!(prop instanceof MappedProperty)) { throw new ExprValidationException( "Unrecognized property '" + identNode.getFullUnresolvedName() + "'"); } MappedProperty mappedProperty = (MappedProperty) prop; if (mappedProperty.getPropertyNameAtomic().toLowerCase().equals(SYSTEM_PROPETIES_NAME)) { return System.getProperty(mappedProperty.getKey()); } } else { ExprNode exprNode = (ExprNode) value; ExprEvaluator evaluator = exprNode.getExprEvaluator(); if (evaluator == null) { throw new ExprValidationException( "Failed to evaluate expression '" + exprNode.toExpressionString() + "'"); } value = evaluator.evaluate(null, true, null); } } if (value == null) { return null; } if (value.getClass() == type) { return value; } if (JavaClassHelper.isAssignmentCompatible(value.getClass(), type)) { if (forceNumeric && JavaClassHelper.getBoxedType(value.getClass()) != JavaClassHelper.getBoxedType(type) && JavaClassHelper.isNumeric(type) && JavaClassHelper.isNumeric(value.getClass())) { value = JavaClassHelper.coerceBoxed((Number) value, JavaClassHelper.getBoxedType(type)); } return value; } if (JavaClassHelper.isSubclassOrImplementsInterface(value.getClass(), type)) { return value; } if (type.isArray()) { if (!(value instanceof Collection)) { throw new ExprValidationException("Property '" + propertyName + "' of class " + JavaClassHelper.getClassNameFullyQualPretty(containingType) + " expects an array but receives a value of type " + value.getClass().getName()); } Object[] items = ((Collection) value).toArray(); Object coercedArray = Array.newInstance(type.getComponentType(), items.length); for (int i = 0; i < items.length; i++) { Object coercedValue = coerceProperty(propertyName + " (array element)", type, items[i], type.getComponentType(), engineImportService, false); Array.set(coercedArray, i, coercedValue); } return coercedArray; } if (!(value instanceof Map)) { throw new ExprValidationException("Property '" + propertyName + "' of class " + JavaClassHelper.getClassNameFullyQualPretty(containingType) + " expects an " + JavaClassHelper.getClassNameFullyQualPretty(type) + " but receives a value of type " + value.getClass().getName()); } Map<String, Object> props = (Map<String, Object>) value; return instantiatePopulateObject(props, type, engineImportService); }
From source file:javadz.beanutils.PropertyUtilsBean.java
/** * Return the Java Class representing the property type of the specified * property, or <code>null</code> if there is no such property for the * specified bean. This method follows the same name resolution rules * used by <code>getPropertyDescriptor()</code>, so if the last element * of a name reference is indexed, the type of the property itself will * be returned. If the last (or only) element has no property with the * specified name, <code>null</code> is returned. * * @param bean Bean for which a property descriptor is requested * @param name Possibly indexed and/or nested name of the property for * which a property descriptor is requested * @return The property type/*from www. ja va2 s.c o m*/ * * @exception IllegalAccessException if the caller does not have * access to the property accessor method * @exception IllegalArgumentException if <code>bean</code> or * <code>name</code> is null * @exception IllegalArgumentException if a nested reference to a * property returns null * @exception InvocationTargetException if the property accessor method * throws an exception * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Class getPropertyType(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'"); } // Resolve nested references while (resolver.hasNested(name)) { String next = resolver.next(name); Object nestedBean = getProperty(bean, next); if (nestedBean == null) { throw new NestedNullException( "Null property value for '" + next + "' on bean class '" + bean.getClass() + "'"); } bean = nestedBean; name = resolver.remove(name); } // Remove any subscript from the final name value name = resolver.getProperty(name); // Special handling for DynaBeans if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { return (null); } Class type = descriptor.getType(); if (type == null) { return (null); } else if (type.isArray()) { return (type.getComponentType()); } else { return (type); } } PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { return (null); } else if (descriptor instanceof IndexedPropertyDescriptor) { return (((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType()); } else if (descriptor instanceof MappedPropertyDescriptor) { return (((MappedPropertyDescriptor) descriptor).getMappedPropertyType()); } else { return (descriptor.getPropertyType()); } }
From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java
/** * The root element being read is defined by schema/JAXB; however its contents are known by * schema/JAXB. Therefore we use unmarshal by the declared type (This method is used to * unmarshal rpc elements)//from w ww . j a v a2 s.c o m * * @param u Unmarshaller * @param reader XMLStreamReader * @param type Class * @return Object * @throws WebServiceException */ public static Object unmarshalByType(final Unmarshaller u, final XMLStreamReader reader, final Class type, final boolean isList, final JAXBUtils.CONSTRUCTION_TYPE ctype) throws WebServiceException { if (DEBUG_ENABLED) { log.debug("Invoking unmarshalByType."); log.debug(" type = " + type); log.debug(" isList = " + isList); log.debug(" ctype = " + ctype); } return AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { // Unfortunately RPC is type based. Thus a // declared type must be used to unmarshal the xml. Object jaxb; if (!isList) { // case: We are not unmarshalling an xsd:list but an Array. if (type.isArray()) { // If the context is created using package // we will not have common arrays or type array in the context // but there is not much we can do about it so seralize it as // usual if (ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CONTEXT_PATH) { if (DEBUG_ENABLED) { log.debug("Unmarshal Array via BY_CONTEXT_PATH approach"); } jaxb = u.unmarshal(reader, type); } // list on client array on server, Can happen only in start from java // case. else if ((ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY)) { // The type could be any Object or primitive //process primitives first //first verify if we have a primitive type associated in the array. //array could be single dimension or multi dimension. Class cType = type.getComponentType(); while (cType.isArray()) { cType = cType.getComponentType(); } if (cType.isPrimitive()) { if (DEBUG_ENABLED) { log.debug("Unmarshal Array of primitive via BY_CLASS_ARRAY approach"); } jaxb = u.unmarshal(reader, type); } // process non primitive // I will first unmarshall the xmldata to a String[] // Then use the unmarshalled jaxbElement to create // proper type Object Array. else { if (DEBUG_ENABLED) { log.debug("Unmarshal Array of non-primitive via BY_CLASS_ARRAY approach"); } jaxb = unmarshalArray(reader, u, type); } } else { if (DEBUG_ENABLED) { log.debug("Unmarshal Array"); } jaxb = u.unmarshal(reader, type); } } else if (type.isEnum()) { // When JAXBContext is created using a context path, it will not // include Enum classes. // These classes have @XmlEnum annotation but not @XmlType/@XmlElement, // so the user will see MarshallingEx, class not known to ctxt. // // This is a jax-b defect, for now this fix is in place to pass CTS. // This only fixes the // situation where the enum is the top-level object (e.g., message-part // in rpc-lit scenario) // // Sample of what enum looks like: // @XmlEnum public enum EnumString { // @XmlEnumValue("String1") STRING_1("String1"), // @XmlEnumValue("String2") STRING_2("String2"); // // public static getValue(String){} <-- resolves a "value" to an emum // object // ... } if (DEBUG_ENABLED) { log.debug("Unmarshalling " + type.getName() + " as Enum"); } JAXBElement<String> enumValue = u.unmarshal(reader, XmlEnumUtils.getConversionType(type)); if (enumValue != null) { jaxb = XmlEnumUtils.fromValue(type, enumValue.getValue()); } else { jaxb = null; } } //Normal case: We are not unmarshalling a xsd:list or Array else { if (DEBUG_ENABLED) { log.debug("Unmarshalling normal case (not array, not xsd:list, not enum)"); } jaxb = u.unmarshal(reader, type); } } else { // If this is an xsd:list, we need to return the appropriate // list or array (see NOTE above) // First unmarshal as a String //Second convert the String into a list or array if (DEBUG_ENABLED) { log.debug("Unmarshalling xsd:list"); } jaxb = unmarshalAsListOrArray(reader, u, type); } if (log.isDebugEnabled()) { Class cls; if (jaxb == null) { if (DEBUG_ENABLED) { log.debug("End unmarshalByType returning null object"); } } else if (jaxb instanceof JAXBElement) { JAXBElement jbe = (JAXBElement) jaxb; if (DEBUG_ENABLED) { log.debug("End unmarshalByType returning JAXBElement"); log.debug(" Class = " + jbe.getDeclaredType()); log.debug(" QName = " + jbe.getName()); } } else { if (DEBUG_ENABLED) { log.debug("End unmarshalByType returning " + jaxb.getClass()); } } } return jaxb; } catch (OMException e) { throw e; } catch (Throwable t) { throw new OMException(t); } } }); }
From source file:org.apache.bval.jsr.ClassValidator.java
private <T> void initMetaBean(final GroupValidationContext<T> context, final MetaBeanFinder metaBeanFinder, final Class<?> directValueClass) { final boolean collection = Collection.class.isAssignableFrom(directValueClass); final boolean map = Map.class.isAssignableFrom(directValueClass); if (!directValueClass.isArray() && (!collection || Collection.class.cast(context.getValidatedValue()).isEmpty()) && (!map || Map.class.cast(context.getValidatedValue()).isEmpty())) { context.setMetaBean(metaBeanFinder.findForClass(directValueClass)); } else if (collection) { context.setMetaBean(metaBeanFinder .findForClass(Collection.class.cast(context.getValidatedValue()).iterator().next().getClass())); } else if (map) { context.setMetaBean(metaBeanFinder.findForClass( Map.class.cast(context.getValidatedValue()).values().iterator().next().getClass())); } else {/*from ww w .ja v a 2 s . co m*/ context.setMetaBean(metaBeanFinder.findForClass(directValueClass.getComponentType())); } }
From source file:br.com.kproj.salesman.infrastructure.helpers.BeanUtils.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void copyProperty(Object dest, String fieldName, Object value, Identifiable orig) throws IllegalAccessException, InvocationTargetException { if (log.isTraceEnabled()) { createLogCopyProperty(dest, fieldName, value); }/* w ww . ja v a 2 s. c o m*/ if (!orig.getFields().contains(fieldName)) { return; } Object target = dest; int delim = fieldName.lastIndexOf(46); if (delim >= 0) { try { target = getPropertyUtils().getProperty(dest, fieldName.substring(0, delim)); } catch (NoSuchMethodException e) { return; } fieldName = fieldName.substring(delim + 1); if (log.isTraceEnabled()) { log.trace(" Target bean = " + target); log.trace(" Target name = " + fieldName); } } String propName = null; Class type = null; int index = -1; String key = null; propName = fieldName; int i = propName.indexOf(91); if (i >= 0) { int k = propName.indexOf(93); try { index = Integer.parseInt(propName.substring(i + 1, k)); } catch (NumberFormatException e) { } propName = propName.substring(0, i); } int j = propName.indexOf(40); if (j >= 0) { int k = propName.indexOf(41); try { key = propName.substring(j + 1, k); } catch (IndexOutOfBoundsException e) { } propName = propName.substring(0, j); } if (target instanceof DynaBean) { DynaClass dynaClass = ((DynaBean) target).getDynaClass(); DynaProperty dynaProperty = dynaClass.getDynaProperty(propName); if (dynaProperty == null) { return; } type = dynaProperty.getType(); } else { PropertyDescriptor descriptor = null; try { descriptor = getPropertyUtils().getPropertyDescriptor(target, fieldName); if (descriptor == null) return; } catch (NoSuchMethodException e) { return; } type = descriptor.getPropertyType(); if (type == null) { if (log.isTraceEnabled()) { log.trace(" target type for property '" + propName + "' is null, so skipping ths setter"); } return; } } if (log.isTraceEnabled()) { log.trace(" target propName=" + propName + ", type=" + type + ", index=" + index + ", key=" + key); } if (index >= 0) { Converter converter = getConvertUtils().lookup(type.getComponentType()); if (converter != null) { log.trace(" USING CONVERTER " + converter); value = converter.convert(type, value); } try { getPropertyUtils().setIndexedProperty(target, propName, index, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } else if (key != null) { try { getPropertyUtils().setMappedProperty(target, propName, key, value); } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } else { Converter converter = getConvertUtils().lookup(type); if (converter != null && value != null) { log.trace(" USING CONVERTER " + converter); value = converter.convert(type, value); } try { if (value instanceof Map) { Map mapDest = (Map) getPropertyUtils().getSimpleProperty(dest, fieldName); if (mapDest != null) { Map mapOrig = (Map) value; Set entrySet = mapOrig.entrySet(); for (Object object : entrySet) { Entry entryOrig = (Entry) object; if (entryOrig.getValue() instanceof Identifiable) { if (mapDest.containsKey(entryOrig.getKey())) { Object destValue = mapDest.get(entryOrig.getKey()); new BeanUtils().copyProperties(destValue, entryOrig.getValue()); } else { mapDest.put(entryOrig.getKey(), entryOrig.getValue()); } } else { mapDest.put(entryOrig.getKey(), entryOrig.getValue()); } } } else { getPropertyUtils().setSimpleProperty(target, propName, value); } } else { getPropertyUtils().setSimpleProperty(target, propName, value); } } catch (NoSuchMethodException e) { throw new InvocationTargetException(e, "Cannot set " + propName); } } }
From source file:com.github.wshackle.java4cpp.J4CppMain.java
private static String classToJNISignature(Class<?> clss) { if (boolean.class.isAssignableFrom(clss)) { return "Z"; } else if (byte.class.isAssignableFrom(clss)) { return "B"; } else if (char.class.isAssignableFrom(clss)) { return "C"; } else if (short.class.isAssignableFrom(clss)) { return "S"; } else if (int.class.isAssignableFrom(clss)) { return "I"; } else if (long.class.isAssignableFrom(clss)) { return "J"; } else if (float.class.isAssignableFrom(clss)) { return "F"; } else if (double.class.isAssignableFrom(clss)) { return "D"; } else if (void.class.isAssignableFrom(clss)) { return "V"; } else if (clss.isArray()) { return "[" + classToJNISignature(clss.getComponentType()); } else {//w w w .ja v a2 s. co m if (null != clss.getEnclosingClass()) { String s = classToJNISignature(clss.getEnclosingClass()); String s1 = clss.getName(); int dollarIndex = s1.indexOf('$'); return s.substring(0, s.length() - 1) + s1.substring(dollarIndex) + ";"; } return "L" + clss.getCanonicalName().replace(".", "/") + ";"; } }
From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java
@SuppressWarnings("unchecked") public <T> T generateRandom(Class<T> clazz, Map<String, Type> itestGenericMap, ITestContext iTestContext) { Object res;/* w w w.ja v a2 s. com*/ ITestParamState iTestState = iTestContext.getCurrentParam(); if (null != iTestState && null == iTestState.getNames()) { res = iTestConfig.getITestValueConverter().convert(clazz, iTestState.getValue()); } else if (Void.class == clazz || void.class == clazz) { res = null; } else if (String.class == clazz && (null == iTestState || null == iTestState.getNames())) { res = RandomStringUtils.randomAlphanumeric(20); } else if (Long.class == clazz || long.class == clazz) { res = new Long(random.nextLong()); } else if (Integer.class == clazz || int.class == clazz) { res = new Integer(random.nextInt()); } else if (Boolean.class == clazz || boolean.class == clazz) { res = random.nextBoolean() ? Boolean.TRUE : Boolean.FALSE; } else if (Date.class == clazz) { res = new Date(random.nextLong()); } else if (Double.class == clazz || double.class == clazz) { res = random.nextDouble(); } else if (Float.class == clazz || float.class == clazz) { res = random.nextFloat(); } else if (Character.class == clazz || char.class == clazz) { res = RandomStringUtils.random(1).charAt(0); } else if (clazz.isEnum()) { res = clazz.getEnumConstants()[random.nextInt(clazz.getEnumConstants().length)]; } else if (clazz.isArray()) { int size = random.nextInt(RANDOM_MAX - RANDOM_MIN) + RANDOM_MIN; if (null != iTestState && iTestState.getSizeParam() != null) { size = iTestState.getSizeParam(); } Object array = Array.newInstance(clazz.getComponentType(), size); for (int i = 0; i < size; i++) { iTestContext.enter(array, String.valueOf(i)); ITestParamState elementITestState = iTestState == null ? null : iTestState.getElement(String.valueOf(i)); Object value = generateRandom((Type) clazz.getComponentType(), itestGenericMap, iTestContext); Array.set(array, i, value); iTestContext.leave(value); } res = array; } else { res = newInstance(clazz, iTestContext); fillFields(clazz, res, iTestState, Collections.EMPTY_MAP, iTestContext); } return (T) res; }