List of usage examples for java.lang Class getComponentType
public Class<?> getComponentType()
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/*w w w .ja v a 2s.c o 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.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 v a 2 s . co m * @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:org.apache.sling.jcr.resource.internal.helper.JcrPropertyMapCacheEntry.java
/** * Convert the default value to the given type * @param type The type class//from ww w .ja va 2s .c om * @param node The node * @param dynamicClassLoader The classloader * @param <T> The type * @return The converted object */ @SuppressWarnings("unchecked") public <T> T convertToType(final Class<T> type, final Node node, final ClassLoader dynamicClassLoader) { T result = null; try { final boolean targetIsArray = type.isArray(); if (this.isArray) { final Object[] sourceArray = convertToObjectArray(this.getPropertyValue()); if (targetIsArray) { result = (T) convertToArray(sourceArray, type.getComponentType(), node, dynamicClassLoader); } else if (sourceArray.length > 0) { result = convertToType(-1, sourceArray[0], type, node, dynamicClassLoader); } } else { final Object sourceObject = this.getPropertyValue(); if (targetIsArray) { result = (T) convertToArray(new Object[] { sourceObject }, type.getComponentType(), node, dynamicClassLoader); } else { result = convertToType(-1, sourceObject, type, node, dynamicClassLoader); } } } catch (final NumberFormatException vfe) { LOGGER.info("converToType: Cannot convert value of " + this.getPropertyValueOrNull() + " to " + type, vfe); } catch (final IllegalArgumentException vfe) { LOGGER.info("converToType: Cannot convert value of " + this.getPropertyValueOrNull() + " to " + type, vfe); } catch (final ValueFormatException vfe) { LOGGER.info("converToType: Cannot convert value of " + this.getPropertyValueOrNull() + " to " + type, vfe); } catch (RepositoryException re) { LOGGER.info("converToType: Cannot get value of " + this.getPropertyValueOrNull(), re); } // fall back to nothing return result; }
From source file:org.getobjects.appserver.publisher.GoJavaMethod.java
@SuppressWarnings("unchecked") public Object coerceFormValueToArgumentType(final Object[] _v, final Class<?> _argType) { // FIXME: All this isn't nice. Cleanup and do it properly. // FIXME: Cache all the dynamic lookup if (_v == null) return null; if (_argType.isAssignableFrom(_v.getClass())) return _v; int vCount = _v.length; /* check whether the argument is some array-ish thing */ if (_argType.isArray()) { final Class<?> itemType = _argType.getComponentType(); final Object typedArray = java.lang.reflect.Array.newInstance(itemType, vCount); for (int i = 0; i < vCount; i++) { Object[] v = { _v[i] }; Object sv = this.coerceFormValueToArgumentType(v, itemType); java.lang.reflect.Array.set(typedArray, i, sv); }/*www . j a v a2 s .c o m*/ return typedArray; } if (_argType.isAssignableFrom(List.class)) return UList.asList(_v); if (_argType.isAssignableFrom(Set.class)) return new HashSet(UList.asList(_v)); if (_argType.isAssignableFrom(Collection.class)) return UList.asList(_v); /* empty assignment */ if (vCount == 0) { if (!_argType.isPrimitive()) return null; // all objects, return null if (_argType == Boolean.TYPE) return new Boolean(false); if (_argType == Integer.TYPE) return new Integer(-1); if (_argType == Double.TYPE) return new Double(-1.0); if (_argType == Float.TYPE) return new Float(-1.0); if (_argType == Short.TYPE) return new Integer(-1); if (_argType == Long.TYPE) return new Long(-1); log.error("Unexpected primitive arg type: " + _argType); return new GoInternalErrorException("Unexpected primitive type!"); } /* check whether it is a directly assignable type */ if (vCount == 1) { /* some type coercion. Can we reuse anything from KVC here? */ // Note: Go supports various Zope form value formats, e.g. 'age:int' // Check WOServletRequest for more. final Object v = _v[0]; if (_argType.isAssignableFrom(v.getClass())) return v; /* some basic coercion */ if (_argType.isPrimitive()) { if (_argType == Boolean.TYPE) return new Boolean(UObject.boolValue(v)); if (_argType == Integer.TYPE || _argType == Short.TYPE) return new Integer(UObject.intValue(v)); if (_argType == Long.TYPE) return new Long(UObject.intOrLongValue(v).longValue()); } else if (_argType.isAssignableFrom(String.class)) return v.toString(); return v; // might crash } /* error out, return exception as value */ log.error("Cannot convert form value to Java argument " + _argType + ": " + _v); return new GoInternalErrorException("Cannot convert form value to Java parameter"); }
From source file:com.gigaspaces.persistency.metadata.DefaultSpaceDocumentMapper.java
private Object toArray(Class<?> type, BasicDBList value) { int length = value.size() - 1; Object array = Array.newInstance(type.getComponentType(), length); for (int i = 1; i < length + 1; i++) { Object v = fromDBObject(value.get(i)); if (SpaceDocument.class.isAssignableFrom(type.getComponentType())) v = MongoDocumentObjectConverter.instance().toDocumentIfNeeded(v, SpaceDocumentSupport.CONVERT); if (type(type.getComponentType()) == TYPE_SHORT) v = ((Integer) v).shortValue(); Array.set(array, i - 1, v); }// www.j a v a 2 s . c o m return array; }
From source file:com.google.ratel.util.RatelUtils.java
private static Object createDeepInstance(Class type, Set<Class> cyclicDetector) { cyclicDetector.add(type);// w w w . jav a 2 s. c o m //System.out.println("Depth: " + callingDepth); try { Object obj = null; // Handle primitives if (defaultValues.containsKey(type)) { Object defaultValue = defaultValues.get(type); obj = defaultValue; // Handle Arrays } else if (type.isArray()) { Class arrayType = type.getComponentType(); // Check cyclic dependency if (!cyclicDetector.contains(arrayType)) { Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector); Object value = createDeepInstance(arrayType, localCyclicDetector); obj = Array.newInstance(arrayType, 1); Array.set(obj, 0, value); } } else { // Handle pojo obj = type.newInstance(); List<Field> fullFieldList = getAllFields(type); for (Field field : fullFieldList) { Class fieldType = field.getType(); // Check for cyclic dependency if (!cyclicDetector.contains(fieldType)) { Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector); Object fieldObj = createDeepInstance(fieldType, localCyclicDetector); if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } field.set(obj, fieldObj); if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(false); } } } } return obj; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java
/** * Write a {@link Writable}, {@link String}, primitive type, or an array of * the preceding.//from w ww. jav a 2 s . co m * @param out * @param instance * @param declaredClass * @param conf * @throws IOException */ @SuppressWarnings("unchecked") public static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf) throws IOException { Object instanceObj = instance; Class declClass = declaredClass; if (instanceObj == null) { // null instanceObj = new NullInstance(declClass, conf); declClass = Writable.class; } writeClassCode(out, declClass); if (declClass.isArray()) { // array // If bytearray, just dump it out -- avoid the recursion and // byte-at-a-time we were previously doing. if (declClass.equals(byte[].class)) { Bytes.writeByteArray(out, (byte[]) instanceObj); } else if (declClass.equals(Result[].class)) { Result.writeArray(out, (Result[]) instanceObj); } else { //if it is a Generic array, write the element's type if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) { Class<?> componentType = declaredClass.getComponentType(); writeClass(out, componentType); } int length = Array.getLength(instanceObj); out.writeInt(length); for (int i = 0; i < length; i++) { Object item = Array.get(instanceObj, i); writeObject(out, item, item.getClass(), conf); } } } else if (List.class.isAssignableFrom(declClass)) { List list = (List) instanceObj; int length = list.size(); out.writeInt(length); for (int i = 0; i < length; i++) { Object elem = list.get(i); writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf); } } else if (declClass == String.class) { // String Text.writeString(out, (String) instanceObj); } else if (declClass.isPrimitive()) { // primitive type if (declClass == Boolean.TYPE) { // boolean out.writeBoolean(((Boolean) instanceObj).booleanValue()); } else if (declClass == Character.TYPE) { // char out.writeChar(((Character) instanceObj).charValue()); } else if (declClass == Byte.TYPE) { // byte out.writeByte(((Byte) instanceObj).byteValue()); } else if (declClass == Short.TYPE) { // short out.writeShort(((Short) instanceObj).shortValue()); } else if (declClass == Integer.TYPE) { // int out.writeInt(((Integer) instanceObj).intValue()); } else if (declClass == Long.TYPE) { // long out.writeLong(((Long) instanceObj).longValue()); } else if (declClass == Float.TYPE) { // float out.writeFloat(((Float) instanceObj).floatValue()); } else if (declClass == Double.TYPE) { // double out.writeDouble(((Double) instanceObj).doubleValue()); } else if (declClass == Void.TYPE) { // void } else { throw new IllegalArgumentException("Not a primitive: " + declClass); } } else if (declClass.isEnum()) { // enum Text.writeString(out, ((Enum) instanceObj).name()); } else if (Message.class.isAssignableFrom(declaredClass)) { Text.writeString(out, instanceObj.getClass().getName()); ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out)); } else if (Writable.class.isAssignableFrom(declClass)) { // Writable Class<?> c = instanceObj.getClass(); Integer code = CLASS_TO_CODE.get(c); if (code == null) { out.writeByte(NOT_ENCODED); Text.writeString(out, c.getName()); } else { writeClassCode(out, c); } ((Writable) instanceObj).write(out); } else if (Serializable.class.isAssignableFrom(declClass)) { Class<?> c = instanceObj.getClass(); Integer code = CLASS_TO_CODE.get(c); if (code == null) { out.writeByte(NOT_ENCODED); Text.writeString(out, c.getName()); } else { writeClassCode(out, c); } ByteArrayOutputStream bos = null; ObjectOutputStream oos = null; try { bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(instanceObj); byte[] value = bos.toByteArray(); out.writeInt(value.length); out.write(value); } finally { if (bos != null) bos.close(); if (oos != null) oos.close(); } } else { throw new IOException("Can't write: " + instanceObj + " as " + declClass); } }
From source file:com.espertech.esper.event.xml.SchemaXMLEventType.java
private EventPropertyGetter doResolvePropertyGetter(String propertyExpression, boolean allowSimpleProperties) { EventPropertyGetter getter = propertyGetterCache.get(propertyExpression); if (getter != null) { return getter; }// w w w . ja v a 2 s. co m if (!allowSimpleProperties) { // see if this is an indexed property int index = ASTFilterSpecHelper.unescapedIndexOfDot(propertyExpression); if (index == -1) { // parse, can be an indexed property Property property = PropertyParser.parse(propertyExpression, false); if (!property.isDynamic()) { if (!(property instanceof IndexedProperty)) { return null; } IndexedProperty indexedProp = (IndexedProperty) property; getter = this.propertyGetters.get(indexedProp.getPropertyNameAtomic()); if (null == getter) { return null; } EventPropertyDescriptor descriptor = this.propertyDescriptorMap .get(indexedProp.getPropertyNameAtomic()); if (descriptor == null) { return null; } if (!descriptor.isIndexed()) { return null; } if (descriptor.getPropertyType() == NodeList.class) { FragmentFactory fragmentFactory = new FragmentFactoryDOMGetter( this.getEventAdapterService(), this, indexedProp.getPropertyNameAtomic()); return new XPathPropertyArrayItemGetter(getter, indexedProp.getIndex(), fragmentFactory); } } } } if (!isPropertyExpressionXPath) { Property prop = PropertyParser.parse(propertyExpression, false); boolean isDynamic = prop.isDynamic(); if (!isDynamic) { SchemaItem item = prop.getPropertyTypeSchema(schemaModelRoot, this.getEventAdapterService()); if (item == null) { return null; } getter = prop.getGetterDOM(schemaModelRoot, this.getEventAdapterService(), this, propertyExpression); if (getter == null) { return null; } Class returnType = SchemaUtil.toReturnType(item); if ((returnType != Node.class) && (returnType != NodeList.class)) { if (!returnType.isArray()) { getter = new DOMConvertingGetter(propertyExpression, (DOMPropertyGetter) getter, returnType); } else { getter = new DOMConvertingArrayGetter((DOMPropertyGetter) getter, returnType.getComponentType()); } } } else { return prop.getGetterDOM(); } } else { boolean allowFragments = !this.getConfigurationEventTypeXMLDOM().isXPathPropertyExpr(); getter = SchemaXMLPropertyParser.getXPathResolution(propertyExpression, getXPathFactory(), getRootElementName(), rootElementNamespace, schemaModel, this.getEventAdapterService(), this, allowFragments, this.getConfigurationEventTypeXMLDOM().getDefaultNamespace()); } propertyGetterCache.put(propertyExpression, getter); return getter; }
From source file:com.wavemaker.runtime.service.ElementType.java
/** * Create an ElementType with one level of children (populated by looking at the bean properties of javaType). This * method should not be used recursively. *///from www. j av a 2 s . co m public ElementType(String name, Class<?> javaType, boolean isList) { this(name, javaType.getName(), isList); PropertyDescriptor[] pds; pds = PropertyUtils.getPropertyDescriptors(javaType); List<ElementType> elements = new ArrayList<ElementType>(pds.length); for (PropertyDescriptor pd : pds) { if (pd.getName().equals("class")) { continue; } if (pd.getReadMethod() == null && pd.getWriteMethod() == null) { continue; } Class<?> klass; Type type; if (pd.getReadMethod() != null) { klass = pd.getReadMethod().getReturnType(); type = pd.getReadMethod().getGenericReturnType(); } else { klass = pd.getWriteMethod().getParameterTypes()[0]; type = pd.getWriteMethod().getGenericParameterTypes()[0]; } ElementType element; if (klass.isArray()) { element = new ElementType(pd.getName(), klass.getComponentType().getName(), true); } else if (Collection.class.isAssignableFrom(klass) && type instanceof ParameterizedType) { ParameterizedType ptype = (ParameterizedType) type; Type aType = ptype.getActualTypeArguments()[0]; element = new ElementType(pd.getName(), ((Class<?>) aType).getName(), true); } else { element = new ElementType(pd.getName(), klass.getName()); } elements.add(element); } this.properties = elements; }