List of usage examples for java.lang Class getComponentType
public Class<?> getComponentType()
From source file:org.apache.olingo.ext.pojogen.AbstractUtility.java
public String getJavaType(final String typeExpression, final boolean forceCollection) { final StringBuilder res = new StringBuilder(); final EdmTypeInfo edmType = getEdmTypeInfo(typeExpression); final String basepkg = StringUtils.isBlank(basePackage) ? "" : basePackage + "."; if ("Edm.Stream".equals(typeExpression)) { res.append(InputStream.class.getName()); } else if (edmType.isPrimitiveType()) { final Class<?> clazz = EdmPrimitiveTypeFactory.getInstance(edmType.getPrimitiveTypeKind()) .getDefaultType();/*w w w.j a v a2 s. co m*/ if (clazz.isArray()) { res.append(clazz.getComponentType().getName()).append("[]"); } else { res.append(clazz.getName()); } } else if (edmType.isComplexType()) { res.append(basepkg).append(edmType.getFullQualifiedName().getNamespace().toLowerCase()). // namespace append('.').append(TYPE_SUB_PKG).append('.') .append(capitalize(edmType.getComplexType().getName())); // ComplexType capitalized name } else if (edmType.isEntityType()) { res.append(basepkg).append(edmType.getFullQualifiedName().getNamespace().toLowerCase()). // namespace append('.').append(TYPE_SUB_PKG).append('.') .append(capitalize(edmType.getEntityType().getName())); // EntityType capitalized name } else if (edmType.isEnumType()) { res.append(basepkg).append(edmType.getFullQualifiedName().getNamespace().toLowerCase()). // namespace append('.').append(TYPE_SUB_PKG).append('.') .append(capitalize(edmType.getEnumType().getName())); } else { throw new IllegalArgumentException("Invalid type expression '" + typeExpression + "'"); } if (forceCollection || edmType.isCollection()) { if (edmType.isEntityType() || edmType.isComplexType()) { res.append("Collection"); } else { res.insert(0, "org.apache.olingo.ext.proxy.api.PrimitiveCollection<").append(">"); } } return res.toString(); }
From source file:com.basistech.rosette.apimodel.ModelTest.java
private Object createObjectForType(Class<?> type, Type genericParameterType) throws IllegalAccessException, InstantiationException, InvocationTargetException { Object o = null;//from ww w . j a va2 s . com Class firstComponentType = type.isArray() ? type.getComponentType() : type; String typeName = firstComponentType.getSimpleName(); Class parameterArgClass = null; Type[] parameterArgTypes = null; if (genericParameterType != null) { if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; parameterArgTypes = aType.getActualTypeArguments(); for (Type parameterArgType : parameterArgTypes) { if (parameterArgType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) parameterArgType; if (isListString(parameterizedType)) { List<List<String>> rv = Lists.newArrayList(); rv.add(Lists.newArrayList("string")); return rv; } } else { parameterArgClass = (Class) parameterArgType; if ("Map".equals(typeName)) { break; } } } } } if (firstComponentType.isEnum()) { return firstComponentType.getEnumConstants()[0]; } switch (typeName) { case "byte": { if (type.isArray()) { o = "somebytes".getBytes(); } else { o = (byte) '8'; } break; } case "String": case "CharSequence": { o = "foo"; break; } case "long": case "Long": { o = (long) 123456789; break; } case "Double": case "double": { o = 1.0; break; } case "int": case "Integer": { o = 98761234; break; } case "boolean": case "Boolean": { o = false; break; } case "Collection": case "List": { if (parameterArgClass != null) { Object o1 = createObjectForType(parameterArgClass, null); List<Object> list = new ArrayList<>(); list.add(o1); o = list; } break; } case "Object": if (inputStreams) { o = new ByteArrayInputStream(new byte[0]); } else { o = "foo"; } break; case "EnumSet": break; case "Set": { if (parameterArgClass != null) { Object o1 = createObjectForType(parameterArgClass, null); Set<Object> set = new HashSet<>(); set.add(o1); o = set; } break; } case "Map": { if (parameterArgTypes != null && parameterArgTypes.length == 2) { Class keyClass = (Class) parameterArgTypes[0]; Object keyObject = createObject(keyClass); if (keyObject != null) { HashMap<Object, Object> map = new HashMap<>(); map.put(keyObject, null); o = map; } } break; } default: if (parameterArgClass != null) { Constructor[] ctors = parameterArgClass.getDeclaredConstructors(); o = createObject(ctors[0]); } else { Constructor[] ctors = firstComponentType.getDeclaredConstructors(); o = createObject(ctors[0]); } } return o; }
From source file:org.apache.drill.jdbc.proxy.InvocationReporterImpl.java
private String formatValue(final Object value) { final String result; if (null == value) { result = "null"; } else {/*from w w w .j av a2s .co m*/ final Class<?> rawActualType = value.getClass(); if (String.class == rawActualType) { result = formatString((String) value); } else if (rawActualType.isArray() && !rawActualType.getComponentType().isPrimitive()) { // Array of non-primitive type final StringBuilder buffer = new StringBuilder(); /* Decide whether to includes this: buffer.append( formatType( elemType ) ); buffer.append( "[] " ); */ buffer.append("{ "); boolean first = true; for (Object elemVal : (Object[]) value) { if (!first) { buffer.append(", "); } first = false; buffer.append(formatValue(elemVal)); } buffer.append(" }"); result = buffer.toString(); } else if (DriverPropertyInfo.class == rawActualType) { result = formatDriverPropertyInfo((DriverPropertyInfo) value); } else if ( // Is type seen and whose toString() renders value well. false || rawActualType == java.lang.Boolean.class || rawActualType == java.lang.Byte.class || rawActualType == java.lang.Double.class || rawActualType == java.lang.Float.class || rawActualType == java.lang.Integer.class || rawActualType == java.lang.Long.class || rawActualType == java.lang.Short.class || rawActualType == java.math.BigDecimal.class || rawActualType == java.lang.Class.class || rawActualType == java.sql.Date.class || rawActualType == java.sql.Timestamp.class) { result = value.toString(); } else if ( // Is type seen and whose toString() has rendered value well--in cases // seen so far. false || rawActualType == java.util.Properties.class || rawActualType.isEnum()) { result = value.toString(); } else if ( // Is type to warn about (one case). false || rawActualType == org.apache.drill.jdbc.DrillResultSet.class) { printWarningLine("Class " + rawActualType.getName() + " should be an interface." + " (While it's a class, it can't be proxied, and some methods can't" + " be traced.)"); result = value.toString(); } else if ( // Is type to warn about (second case). false || rawActualType == org.apache.hadoop.io.Text.class || rawActualType == org.joda.time.Period.class || rawActualType == org.apache.drill.exec.vector.accessor.sql.TimePrintMillis.class) { printWarningLine("Should " + rawActualType + " be appearing at JDBC interface?"); result = value.toString(); } else { // Is other type--unknown whether it already formats well. // (No handled yet: byte[].) printWarningLine("Unnoted type encountered in formatting (value might" + " not render well): " + rawActualType + "."); result = value.toString(); } } return result; }
From source file:org.apache.struts.config.FormPropertyConfig.java
/** * <p>Return an object representing the initial value of this property. * This is calculated according to the following algorithm:</p> * * <ul>/*from w w w .j a v a 2 s. com*/ * * <li>If the value you have specified for the <code>type</code> property * represents an array (i.e. it ends with "[]"): * * <ul> * * <li>If you have specified a value for the <code>initial</code> * property, <code>ConvertUtils.convert</code> will be called to convert * it into an instance of the specified array type.</li> * * <li>If you have not specified a value for the <code>initial</code> * property, an array of the length specified by the <code>size</code> * property will be created. Each element of the array will be * instantiated via the zero-args constructor on the specified class (if * any). Otherwise, <code>null</code> will be returned.</li> * * </ul></li> * * <li>If the value you have specified for the <code>type</code> property * does not represent an array: * * <ul> * * <li>If you have specified a value for the <code>initial</code> * property, <code>ConvertUtils.convert</code> will be called to convert * it into an object instance.</li> * * <li>If you have not specified a value for the <code>initial</code> * attribute, Struts will instantiate an instance via the zero-args * constructor on the specified class (if any). Otherwise, * <code>null</code> will be returned.</li> * * </ul></li> * * </ul> */ public Object initial() { Object initialValue = null; try { Class clazz = getTypeClass(); if (clazz.isArray()) { if (initial != null) { initialValue = ConvertUtils.convert(initial, clazz); } else { initialValue = Array.newInstance(clazz.getComponentType(), size); if (!(clazz.getComponentType().isPrimitive())) { for (int i = 0; i < size; i++) { try { Array.set(initialValue, i, clazz.getComponentType().newInstance()); } catch (Throwable t) { log.error("Unable to create instance of " + clazz.getName() + " for property=" + name + ", type=" + type + ", initial=" + initial + ", size=" + size + "."); //FIXME: Should we just dump the entire application/module ? } } } } } else { if (initial != null) { initialValue = ConvertUtils.convert(initial, clazz); } else { initialValue = clazz.newInstance(); } } } catch (Throwable t) { initialValue = null; } return (initialValue); }
From source file:com.alibaba.dubbo.governance.web.common.module.screen.Restful.java
public void execute(Map<String, Object> context) throws Throwable { if (context.get(WebConstants.CURRENT_USER_KEY) != null) { User user = (User) context.get(WebConstants.CURRENT_USER_KEY); currentUser = user;//w w w. ja va 2 s . c o m operator = user.getUsername(); role = user.getRole(); context.put(WebConstants.CURRENT_USER_KEY, user); } operatorAddress = (String) context.get("request.remoteHost"); context.put("operator", operator); context.put("operatorAddress", operatorAddress); context.put("currentRegistry", currentRegistry); String httpMethod = (String) context.get("request.method"); String method = (String) context.get("_method"); String contextPath = (String) context.get("request.contextPath"); context.put("rootContextPath", new RootContextPath(contextPath)); // ?Method if (method == null || method.length() == 0) { String id = (String) context.get("id"); if (id == null || id.length() == 0) { method = "index"; } else { method = "show"; } } if ("index".equals(method)) { if ("post".equalsIgnoreCase(httpMethod)) { method = "create"; } } else if ("show".equals(method)) { if ("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // ????PUTPOST method = "update"; } else if ("delete".equalsIgnoreCase(httpMethod)) { // ????DELETE? method = "delete"; } } context.put("_method", method); try { Method m = null; try { m = getClass().getMethod(method, new Class<?>[] { Map.class }); } catch (NoSuchMethodException e) { for (Method mtd : getClass().getMethods()) { if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().equals(method)) { m = mtd; break; } } if (m == null) { throw e; } } if (m.getParameterTypes().length > 2) { throw new IllegalStateException("Unsupport restful method " + m); } else if (m.getParameterTypes().length == 2 && (m.getParameterTypes()[0].equals(Map.class) || !m.getParameterTypes()[1].equals(Map.class))) { throw new IllegalStateException("Unsupport restful method " + m); } Object r; if (m.getParameterTypes().length == 0) { r = m.invoke(this, new Object[0]); } else { Object value; Class<?> t = m.getParameterTypes()[0]; if (Map.class.equals(t)) { value = context; } else if (isPrimitive(t)) { String id = (String) context.get("id"); value = convertPrimitive(t, id); } else if (t.isArray() && isPrimitive(t.getComponentType())) { String id = (String) context.get("id"); String[] ids = id == null ? new String[0] : id.split("[.+]+"); value = Array.newInstance(t.getComponentType(), ids.length); for (int i = 0; i < ids.length; i++) { Array.set(value, i, convertPrimitive(t.getComponentType(), ids[i])); } } else { value = t.newInstance(); for (Method mtd : t.getMethods()) { if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().startsWith("set") && mtd.getParameterTypes().length == 1) { String p = mtd.getName().substring(3, 4).toLowerCase() + mtd.getName().substring(4); Object v = context.get(p); if (v == null) { if ("operator".equals(p)) { v = operator; } else if ("operatorAddress".equals(p)) { v = (String) context.get("request.remoteHost"); } } if (v != null) { try { mtd.invoke(value, new Object[] { CompatibleTypeUtils.compatibleTypeConvert(v, mtd.getParameterTypes()[0]) }); } catch (Throwable e) { logger.warn(e.getMessage(), e); } } } } } if (m.getParameterTypes().length == 1) { r = m.invoke(this, new Object[] { value }); } else { r = m.invoke(this, new Object[] { value, context }); } } if (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class) { context.put("rundata.layout", "redirect"); context.put("rundata.target", "redirect"); context.put("success", r == null || ((Boolean) r).booleanValue()); if (context.get("redirect") == null) { context.put("redirect", getDefaultRedirect(context, method)); } } else if (m.getReturnType() == String.class) { String redirect = (String) r; if (redirect == null) { redirect = getDefaultRedirect(context, method); } if (context.get("chain") != null) { context.put("rundata.layout", "home"); context.put("rundata.target", "home"); } else { context.put("rundata.redirect", redirect); } } else { context.put("rundata.layout", method); context.put("rundata.target", context.get("rundata.target") + "/" + method); } } catch (Throwable e) { if (e instanceof InvocationTargetException) { throw ((InvocationTargetException) e).getTargetException(); } // if (e instanceof InvocationTargetException) { // e = ((InvocationTargetException) e).getTargetException(); // } // logger.warn(e.getMessage(), e); // context.put("rundata.layout", "redirect"); // context.put("rundata.target", "redirect"); // context.put("success", false); // context.put("exception", e); // context.put("redirect", getDefaultRedirect(context, method)); } }
From source file:javadz.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//from w w w .j av a2 s . co m * @param pattern The convertion pattern * @return the converted value * * @throws org.apache.commons.beanutils.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 + " 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); }
From source file:com.interface21.beans.factory.support.AbstractBeanFactory.java
/** * Given a PropertyValue, return a value, resolving any references to other * beans in the factory if necessary. The value could be: * <li>An ordinary object or null, in which case it's left alone * <li>A RuntimeBeanReference, which must be resolved * <li>A ManagedList. This is a special collection that may contain * RuntimeBeanReferences that will need to be resolved. * <li>A ManagedMap. In this case the value may be a reference that * must be resolved./*from w w w.j av a2 s.c o m*/ * If the value is a simple object, but the property takes a Collection type, * the value must be placed in a list. */ private Object resolveValueIfNecessary(BeanWrapper bw, Map newlyCreatedBeans, PropertyValue pv) throws BeansException { Object val; // Now we must check each PropertyValue to see whether it // requires a runtime reference to another bean to be resolved. // If it does, we'll attempt to instantiate the bean and set the reference. if (pv.getValue() != null && (pv.getValue() instanceof RuntimeBeanReference)) { RuntimeBeanReference ref = (RuntimeBeanReference) pv.getValue(); val = resolveReference(pv.getName(), ref, newlyCreatedBeans); } else if (pv.getValue() != null && (pv.getValue() instanceof ManagedList)) { // Convert from managed list. This is a special container that // may contain runtime bean references. // May need to resolve references val = resolveManagedList(pv.getName(), (ManagedList) pv.getValue(), newlyCreatedBeans); } else if (pv.getValue() != null && (pv.getValue() instanceof ManagedMap)) { // Convert from managed map. This is a special container that // may contain runtime bean references as values. // May need to resolve references ManagedMap mm = (ManagedMap) pv.getValue(); val = resolveManagedMap(pv.getName(), mm, newlyCreatedBeans); } else { // It's an ordinary property. Just copy it. val = pv.getValue(); } // If it's an array type, we may have to massage type // of collection. We'll start with ManagedList. // We may also have to convert array elements from Strings // TODO consider refactoring into BeanWrapperImpl? if (val != null && val instanceof ManagedList && bw.getPropertyDescriptor(pv.getName()).getPropertyType().isArray()) { // It's an array Class arrayClass = bw.getPropertyDescriptor(pv.getName()).getPropertyType(); Class componentType = arrayClass.getComponentType(); List l = (List) val; val = managedListToArray(bw, pv, val, componentType, l); } return val; }
From source file:org.bitpipeline.lib.friendlyjson.JSONEntity.java
/** Des-serialize a JSON object. * @throws JSONException/* www . j a v a 2 s . c o m*/ * @throws JSONMappingException */ public JSONEntity(JSONObject json) throws JSONMappingException { if (json == null) return; Class<?> clazz = this.getClass(); List<Field> declaredFields = new ArrayList<Field>(); do { Field[] fields = clazz.getDeclaredFields(); declaredFields.addAll(Arrays.asList(fields)); clazz = clazz.getSuperclass(); } while (clazz != null && !clazz.isAssignableFrom(JSONEntity.class)); for (Field field : declaredFields) { if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { // don't care about transient fields. continue; } String fieldName = field.getName(); if (fieldName.equals("this$0")) continue; boolean accessible = field.isAccessible(); if (!accessible) field.setAccessible(true); Class<?> type = field.getType(); if (type.isArray()) { Class<?> componentClass = type.getComponentType(); JSONArray jsonArray = null; try { jsonArray = json.getJSONArray(fieldName); } catch (JSONException e) { // no data for this field found. continue; } int size = jsonArray.length(); Object array = Array.newInstance(componentClass, size); for (int i = 0; i < size; i++) { try { Object item = fromJson(componentClass, jsonArray.get(i)); Array.set(array, i, item); } catch (Exception e) { System.err.println("Invalid array component for class " + this.getClass().getName() + " field " + field.getName() + "::" + field.getType().getName()); } } try { field.set(this, array); } catch (Exception e) { throw new JSONMappingException(e); } } else if (JSONEntity.class.isAssignableFrom(type)) { try { Object entity = readJSONEntity(type, json.getJSONObject(fieldName)); field.set(this, entity); } catch (JSONException e) { // keep going.. the json representation doesn't have value for this field. } catch (Exception e) { throw new JSONMappingException(e); } } else { FieldSetter setter = JSON_READERS.get(type.getName()); if (setter != null) { try { setter.setField(this, field, json, fieldName); } catch (JSONException e) { // do nothing. We just didn't receive data for this field } catch (Exception e) { throw new JSONMappingException(e); } } else { Object jsonObj; try { jsonObj = json.get(fieldName); } catch (Exception e) { jsonObj = null; } if (jsonObj != null) { Object value = fromJson(type, jsonObj); try { field.set(this, value); } catch (Exception e) { e.printStackTrace(); } } else { System.err.println("No setter for " + field); } } } if (!accessible) field.setAccessible(false); } }
From source file:de.escalon.hypermedia.spring.ActionInputParameter.java
private Object[] getPossibleValues(MethodParameter methodParameter, AnnotatedParameters actionDescriptor) { try {//from w w w. j ava2 s . co m Class<?> parameterType = methodParameter.getNestedParameterType(); 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> 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()) { AnnotatedParameter parameterValue = actionDescriptor.getAnnotatedParameter(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.ewcms.common.query.mongo.PropertyConvert.java
/** * ?{@link RuntimeException}//from ww w . ja va2s .c o m * * @param name ???{@literal null} * @return {@value Class<?>} */ public Class<?> getPropertyType(String propertyName) { if (!StringUtils.hasText(propertyName)) { throw new IllegalArgumentException("Property's name must not null or empty!"); } String[] names = StringUtils.tokenizeToStringArray(propertyName, NESTED); Class<?> type = beanClass; PropertyDescriptor pd = null; for (String name : names) { pd = BeanUtils.getPropertyDescriptor(type, name); if (pd == null) { logger.error("\"{}\" property isn't exist.", propertyName); throw new RuntimeException(propertyName + " property isn't exist."); } type = pd.getPropertyType(); } if (type.isArray()) { return type.getComponentType(); } if (Collection.class.isAssignableFrom(type)) { Method method = pd.getReadMethod(); if (method == null) { logger.error("\"{}\" property is not read method.", propertyName); throw new RuntimeException(propertyName + " property is not read method."); } ParameterizedType returnType = (ParameterizedType) method.getGenericReturnType(); if (returnType.getActualTypeArguments().length > 0) { return (Class<?>) returnType.getActualTypeArguments()[0]; } logger.error("\"{}\" property is collection,but it's not generic.", propertyName); throw new RuntimeException(propertyName + " property is collection,but it's not generic."); } return type; }