List of usage examples for java.lang Class getComponentType
public Class<?> getComponentType()
From source file:com.jaspersoft.jasperserver.remote.utils.RepositoryHelper.java
protected static Object getMultiParameterValues(JRParameter parameter, Collection values) { Object parameterValue;/*from w ww . ja va 2 s . co m*/ Class parameterType = parameter.getValueClass(); if (parameterType.equals(Object.class) || parameterType.equals(Collection.class) || parameterType.equals(Set.class) || parameterType.equals(List.class)) { Collection paramValues; if (parameterType.equals(List.class)) { //if the parameter type is list, use a list paramValues = new ArrayList(values.size()); } else { //else use an ordered set paramValues = new ListOrderedSet(); } Class componentType = parameter.getNestedType(); for (Iterator it = values.iterator(); it.hasNext();) { Object val = (Object) it.next(); Object paramValue; if (componentType == null || !(val instanceof String)) { //no conversion if no nested type set for the parameter paramValue = val; } else { paramValue = stringToValue((String) val, componentType); } paramValues.add(paramValue); } parameterValue = paramValues; } else if (parameterType.isArray()) { Class componentType = parameterType.getComponentType(); parameterValue = Array.newInstance(componentType, values.size()); int idx = 0; for (Iterator iter = values.iterator(); iter.hasNext(); ++idx) { Object val = iter.next(); Object paramValue; if (val instanceof String) { paramValue = stringToValue((String) val, componentType); } else { paramValue = val; } Array.set(parameterValue, idx, paramValue); } } else { parameterValue = values; } return parameterValue; }
From source file:com.github.erchu.beancp.MapperImpl.java
@Override @SuppressWarnings("TooBroadCatch") public <S, D> Optional<D> mapIfMapperAvailable(final S source, final Class<D> destinationClass) throws MappingException { notNull(source, "source"); notNull(destinationClass, "destinationClass"); Class sourceClass = source.getClass(); try {/*from w w w . ja v a 2 s. co m*/ Converter<S, D> converter = (Converter<S, D>) MapperExecutorSelector .getBestMatchingConverter(sourceClass, destinationClass, _converters); if (converter != null) { if (sourceClass.isArray() && sourceClass.getComponentType().isPrimitive()) { Object[] sourceWrapper = getArrayOfPrimitiveTypeWrapper(sourceClass, source); return Optional.of(((Converter<Object, D>) converter).convert(this, sourceWrapper)); } else { return Optional.of(converter.convert(this, source)); } } DeclarativeMapImpl<S, D> map = (DeclarativeMapImpl<S, D>) MapperExecutorSelector .getBestMatchingDeclarativeMap(sourceClass, destinationClass, _maps); D destination = null; if (map != null && map.getDestinationObjectBuilder() != null) { destination = constructObjectUsingDestinationObjectBuilder(map.getDestinationObjectBuilder(), destinationClass); } // if DeclarativeMapImpl is not available or has no specific destination object builder if (destination == null) { destination = constructObjectUsingDefaultConstructor(destinationClass); } if (mapIfMapperAvailable(source, destination)) { return Optional.of(destination); } else { return Optional.empty(); } } catch (Exception ex) { throw new MappingException(String.format("Failed to map from %s to %s", sourceClass, destinationClass), ex); } }
From source file:com.nginious.http.serialize.JsonDeserializerCreator.java
/** * Creates a JSON deserializer for the specified bean class unless a deserializer has already * been created. Created deserializers are cached and returned on subsequent calls to this method. * //from w ww . j ava 2 s. c om * @param <T> class type for bean * @param beanClazz bean class for which a deserializer should be created * @return the created deserializer * @throws SerializerFactoryException if unable to create deserializer or class is not a bean */ @SuppressWarnings("unchecked") protected <T> JsonDeserializer<T> create(Class<T> beanClazz) throws SerializerFactoryException { JsonDeserializer<T> deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz); if (deserializer != null) { return deserializer; } try { synchronized (this) { deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz); if (deserializer != null) { return deserializer; } checkDeserializability(beanClazz, "json"); String intBeanClazzName = Serialization.createInternalClassName(beanClazz); Method[] methods = beanClazz.getMethods(); String intDeserializerClazzName = new StringBuffer(intBeanClazzName).append("JsonDeserializer") .toString(); // Create class ClassWriter writer = new ClassWriter(0); String signature = Serialization .createClassSignature("com/nginious/http/serialize/JsonDeserializer", intBeanClazzName); writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intDeserializerClazzName, signature, "com/nginious/http/serialize/JsonDeserializer", null); // Create constructor Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonDeserializer"); // Create deserialize method MethodVisitor visitor = createDeserializeMethod(writer, intBeanClazzName); for (Method method : methods) { Serializable info = method.getAnnotation(Serializable.class); boolean canDeserialize = info == null || (info != null && info.deserialize() && info.types().indexOf("json") > -1); if (canDeserialize && method.getName().startsWith("set") && method.getReturnType().equals(void.class) && method.getParameterTypes().length == 1) { Class<?>[] parameterTypes = method.getParameterTypes(); Class<?> parameterType = parameterTypes[0]; if (parameterType.isArray()) { Class<?> arrayType = parameterType.getComponentType(); if (arrayType.equals(boolean.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeBooleanArray", "[Z", "[Z", intBeanClazzName, method.getName()); } else if (arrayType.equals(double.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDoubleArray", "[D", "[D", intBeanClazzName, method.getName()); } else if (arrayType.equals(float.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeFloatArray", "[F", "[F", intBeanClazzName, method.getName()); } else if (arrayType.equals(int.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeIntArray", "[I", "[I", intBeanClazzName, method.getName()); } else if (arrayType.equals(long.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeLongArray", "[J", "[J", intBeanClazzName, method.getName()); } else if (arrayType.equals(short.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeShortArray", "[S", "[S", intBeanClazzName, method.getName()); } else if (arrayType.equals(String.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeStringArray", "[Ljava/lang/String;", "[Ljava/lang/String;", intBeanClazzName, method.getName()); } } else if (parameterType.isPrimitive()) { if (parameterType.equals(boolean.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeBoolean", "Z", "Z", intBeanClazzName, method.getName()); } else if (parameterType.equals(double.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDouble", "D", "D", intBeanClazzName, method.getName()); } else if (parameterType.equals(float.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeFloat", "F", "F", intBeanClazzName, method.getName()); } else if (parameterType.equals(int.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeInt", "I", "I", intBeanClazzName, method.getName()); } else if (parameterType.equals(long.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeLong", "J", "J", intBeanClazzName, method.getName()); } else if (parameterType.equals(short.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeShort", "S", "S", intBeanClazzName, method.getName()); } } else if (parameterType.equals(Calendar.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeCalendar", "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName, method.getName()); } else if (parameterType.equals(Date.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDate", "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName()); } else if (parameterType.equals(String.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeString", "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName()); } } } visitor.visitVarInsn(Opcodes.ALOAD, 3); visitor.visitInsn(Opcodes.ARETURN); visitor.visitMaxs(5, 4); visitor.visitEnd(); writer.visitEnd(); byte[] clazzBytes = writer.toByteArray(); ClassLoader controllerLoader = null; if (classLoader.hasLoaded(beanClazz)) { controllerLoader = beanClazz.getClassLoader(); } else { controllerLoader = this.classLoader; } Class<?> clazz = Serialization.loadClass(controllerLoader, intDeserializerClazzName.replace('/', '.'), clazzBytes); deserializer = (JsonDeserializer<T>) clazz.newInstance(); deserializers.put(beanClazz, deserializer); return deserializer; } } catch (IllegalAccessException e) { throw new SerializerFactoryException(e); } catch (InstantiationException e) { throw new SerializerFactoryException(e); } }
From source file:com.day.cq.wcm.foundation.forms.MergedValueMap.java
/** * Converts the object to the given type. * @param obj object/*w w w . j a v a 2s . com*/ * @param type type * @return the converted object */ @SuppressWarnings("unchecked") private <T> T convert(Object obj, Class<T> type) { try { if (obj == null) { return null; } else if (type.isAssignableFrom(obj.getClass())) { return (T) obj; } else if (type.isArray()) { return (T) convertToArray(obj, type.getComponentType()); } else if (obj instanceof Calendar && type == String.class) { // simulate jcrValue.getString() return (T) ISO8601.format((Calendar) obj); } else if (type == String.class) { return (T) String.valueOf(obj); } else if (type == Integer.class) { return (T) (Integer) Integer.parseInt(obj.toString()); } else if (type == Long.class) { return (T) (Long) Long.parseLong(obj.toString()); } else if (type == Double.class) { return (T) (Double) Double.parseDouble(obj.toString()); } else if (type == Boolean.class) { return (T) (Boolean) Boolean.parseBoolean(obj.toString()); } else { return null; } } catch (NumberFormatException e) { return null; } }
From source file:org.evosuite.testcase.ArrayStatement.java
/** {@inheritDoc} */ @Override//from w w w . j a v a 2 s . c o m public Throwable execute(Scope scope, PrintStream out) throws InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException { Throwable exceptionThrown = null; // Add array variable to pool try { Class<?> componentType = retval.getComponentClass(); while (componentType.isArray()) componentType = componentType.getComponentType(); retval.setObject(scope, Array.newInstance(componentType, lengths)); } catch (CodeUnderTestException e) { exceptionThrown = e.getCause(); } return exceptionThrown; }
From source file:org.apache.drill.jdbc.proxy.InvocationReporterImpl.java
/** * Renders a type name. Uses simple names for common types (JDBC interfaces * and {code java.lang.*})./* ww w . ja v a 2 s. c o m*/ */ private String formatType(final Class<?> type) { final String result; if (type.isArray()) { result = formatType(type.getComponentType()) + "[]"; } else { // Suppress package name for common (JDBC and java.lang) types, except // when would be ambiguous (e.g., java.sql.Date vs. java.util.Date). if (PACKAGES_TO_ABBREVIATE.contains(type.getPackage())) { int sameSimpleNameCount = 0; for (Package p : PACKAGES_TO_ABBREVIATE) { try { Class.forName(p.getName() + "." + type.getSimpleName()); sameSimpleNameCount++; } catch (ClassNotFoundException e) { // Nothing to do. } } if (1 == sameSimpleNameCount) { result = type.getSimpleName(); } else { // Multiple classes with same simple name, so would be ambiguous to // abbreviate, so use fully qualified name. result = type.getName(); } } else { result = type.getName(); } } return result; }
From source file:de.escalon.hypermedia.action.ActionInputParameter.java
public Object[] getPossibleValues(ActionDescriptor actionDescriptor) { try {/*from ww w . ja v a 2s . co m*/ Class<?> parameterType = getParameterType(); Object[] possibleValues; Class<?> nested; if (Enum[].class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getComponentType().getEnumConstants(); } else if (Enum.class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getEnumConstants(); } else if (Collection.class.isAssignableFrom(parameterType) && Enum.class.isAssignableFrom(nested = TypeDescriptor.nested(methodParameter, 1).getType())) { possibleValues = nested.getEnumConstants(); } else { Select select = methodParameter.getParameterAnnotation(Select.class); if (select != null) { Class<? extends Options> options = select.options(); Options instance = options.newInstance(); List<Object> from = new ArrayList<Object>(); for (String paramName : select.args()) { ActionInputParameter parameterValue = actionDescriptor.getActionInputParameter(paramName); if (parameterValue != null) { from.add(parameterValue.getCallValue()); } } Object[] args = from.toArray(); possibleValues = instance.get(select.value(), args); } else { possibleValues = new Object[0]; } } return possibleValues; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:de.escalon.hypermedia.action.ActionInputParameter.java
public Object[] getPossibleValues(Property property, ActionDescriptor actionDescriptor) { // TODO remove code duplication of getPossibleValues try {/*w w w . j av a2 s . c om*/ Class<?> parameterType = property.getType(); Object[] possibleValues; Class<?> nested; if (Enum[].class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getComponentType().getEnumConstants(); } else if (Enum.class.isAssignableFrom(parameterType)) { possibleValues = parameterType.getEnumConstants(); } else if (Collection.class.isAssignableFrom(parameterType) && Enum.class.isAssignableFrom(nested = TypeDescriptor.nested(property, 1).getType())) { possibleValues = nested.getEnumConstants(); } else { Annotation[][] parameterAnnotations = property.getWriteMethod().getParameterAnnotations(); // setter has exactly one param Select select = getSelectAnnotationFromFirstParam(parameterAnnotations[0]); if (select != null) { Class<? extends Options> optionsClass = select.options(); Options options = optionsClass.newInstance(); // collect call values to pass to options.get List<Object> from = new ArrayList<Object>(); for (String paramName : select.args()) { ActionInputParameter parameterValue = actionDescriptor.getActionInputParameter(paramName); if (parameterValue != null) { from.add(parameterValue.getCallValue()); } } Object[] args = from.toArray(); possibleValues = options.get(select.value(), args); } else { possibleValues = new Object[0]; } } return possibleValues; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.examples.with.different.packagename.testcarver.AbstractConverter.java
/** * Provide a String representation of a <code>java.lang.Class</code>. * @param type The <code>java.lang.Class</code>. * @return The String representation./*from ww w .j a v a 2 s . co m*/ */ String toString(Class type) { String typeName = null; if (type == null) { typeName = "null"; } else if (type.isArray()) { Class elementType = type.getComponentType(); int count = 1; while (elementType.isArray()) { elementType = elementType.getComponentType(); count++; } typeName = elementType.getName(); for (int i = 0; i < count; i++) { typeName += "[]"; } } else { typeName = type.getName(); } if (typeName.startsWith("java.lang.") || typeName.startsWith("java.util.") || typeName.startsWith("java.math.")) { typeName = typeName.substring("java.lang.".length()); } else if (typeName.startsWith(PACKAGE)) { typeName = typeName.substring(PACKAGE.length()); } return typeName; }
From source file:org.enerj.apache.commons.beanutils.locale.LocaleConvertUtilsBean.java
/** * Convert an array of specified values to an array of objects of the * specified class (if possible) using the convertion pattern. * * @param values Value to be converted (may be null) * @param clazz Java array or element class to be converted to * @param locale The locale/*ww w . ja v a 2 s . c o m*/ * @param pattern The convertion pattern * * @exception ConversionException if thrown by an underlying Converter */ public Object convert(String values[], Class clazz, Locale locale, String pattern) { Class type = clazz; if (clazz.isArray()) { type = clazz.getComponentType(); } if (log.isDebugEnabled()) { log.debug("Convert String[" + values.length + "] to class " + type.getName() + "[] using " + locale.toString() + " locale and " + pattern + " pattern"); } Object array = Array.newInstance(type, values.length); for (int i = 0; i < values.length; i++) { Array.set(array, i, convert(values[i], type, locale, pattern)); } return (array); }