List of usage examples for java.lang Class isArray
@HotSpotIntrinsicCandidate public native boolean isArray();
From source file:com.sinosoft.one.data.jade.rowmapper.DefaultRowMapperFactory.java
public RowMapper getRowMapper(StatementMetaData modifier) { RowHandler rowHandler = modifier.getAnnotation(RowHandler.class); if (rowHandler != null) { if (rowHandler.rowMapper() != RowHandler.ByDefault.class) { try { RowMapper rowMapper = rowHandler.rowMapper().newInstance(); if (logger.isInfoEnabled()) { logger.info("using rowMapper " + rowMapper + " for " + modifier); }/*from ww w .j a v a 2s . c om*/ return rowMapper; } catch (Exception ex) { throw new BeanInstantiationException(rowHandler.rowMapper(), ex.getMessage(), ex); } } } // Class<?> returnClassType = modifier.getMethod().getReturnType(); Class<?> rowType = getRowType(modifier); // BUGFIX: SingleColumnRowMapper ? Primitive Type if (rowType.isPrimitive()) { rowType = ClassUtils.primitiveToWrapper(rowType); } // ? RowMapper RowMapper rowMapper; // ?(?2Map) if (TypeUtils.isColumnType(rowType)) { if (returnClassType == Map.class) { rowMapper = new MapEntryColumnRowMapper(modifier, rowType); } else { rowMapper = new SingleColumnRowMapper(rowType); } } // Bean?????? else { if (rowType == Map.class) { rowMapper = new ColumnMapRowMapper(); } else if (rowType.isArray()) { rowMapper = new ArrayRowMapper(rowType); } else if ((rowType == List.class) || (rowType == Collection.class)) { rowMapper = new ListRowMapper(modifier); } else if (rowType == Set.class) { rowMapper = new SetRowMapper(modifier); } else { boolean checkColumns = (rowHandler == null) ? false : rowHandler.checkColumns(); boolean checkProperties = (rowHandler == null) ? false : rowHandler.checkProperties(); String key = rowType.getName() + "[checkColumns=" + checkColumns + "&checkProperties=" + checkProperties + "]"; rowMapper = rowMappers.get(key); if (rowMapper == null) { rowMapper = new BeanPropertyRowMapper(rowType, checkColumns, checkProperties); // jade's BeanPropertyRowMapper here rowMappers.put(key, rowMapper); } } // DAOMaprowMapper?Map.Entry if (returnClassType == Map.class) { rowMapper = new MapEntryRowMapper(modifier, rowMapper); } } if (logger.isInfoEnabled()) { logger.info("using rowMapper " + rowMapper + " for " + modifier); } return rowMapper; }
From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java
/** * Returns the literal value of an object that is suitable for inclusion in Java Source code. * * <p>//from w w w . ja va 2s . c o m * Supports all types that {@link Annotation} value can have. * </p> * * * @throws IllegalArgumentException if the type of the object does not have a java literal form. */ public static String asLiteral(final Object value) throws IllegalArgumentException { final Class<?> clazz = value.getClass(); if (clazz.isArray()) { final StringBuilder sb = new StringBuilder(); final Object[] array = (Object[]) value; sb.append("new " + clazz.getComponentType().getCanonicalName() + "[] {"); boolean first = true; for (final Object object : array) { if (first) { first = false; } else { sb.append(','); } sb.append(asLiteral(object)); } sb.append('}'); return sb.toString(); } if (value instanceof Boolean) { return JBooleanLiteral.get(((Boolean) value).booleanValue()).toSource(); } else if (value instanceof Byte) { return JIntLiteral.get(((Byte) value).byteValue()).toSource(); } else if (value instanceof Character) { return JCharLiteral.get(((Character) value).charValue()).toSource(); } else if (value instanceof Class<?>) { return ((Class<?>) (Class<?>) value).getCanonicalName() + ".class"; } else if (value instanceof Double) { return JDoubleLiteral.get(((Double) value).doubleValue()).toSource(); } else if (value instanceof Enum) { return value.getClass().getCanonicalName() + "." + ((Enum<?>) value).name(); } else if (value instanceof Float) { return JFloatLiteral.get(((Float) value).floatValue()).toSource(); } else if (value instanceof Integer) { return JIntLiteral.get(((Integer) value).intValue()).toSource(); } else if (value instanceof Long) { return JLongLiteral.get(((Long) value).longValue()).toSource(); } else if (value instanceof String) { return '"' + Generator.escape((String) value) + '"'; } else { // TODO(nchalko) handle Annotation types throw new IllegalArgumentException(value.getClass() + " can not be represented as a Java Literal."); } }
From source file:com.gzj.tulip.jade.rowmapper.DefaultRowMapperFactory.java
@Override public RowMapper getRowMapper(StatementMetaData smd) { RowHandler rowHandler = smd.getAnnotation(RowHandler.class); // ? RowMapper RowMapper rowMapper = null;//from w w w. jav a 2 s . c o m if (rowHandler != null) { if (rowHandler.rowMapper() != RowHandler.NotSettingRowMapper.class) { try { rowMapper = rowHandler.rowMapper().newInstance(); } catch (Exception ex) { throw new BeanInstantiationException(rowHandler.rowMapper(), ex.getMessage(), ex); } } else if (rowHandler.rowMapperFactory() != RowHandler.NotSettingRowMapperFactory.class) { try { RowMapperFactory rowMapperFactory = rowHandler.rowMapperFactory().newInstance(); rowMapper = rowMapperFactory.getRowMapper(smd); } catch (Exception ex) { throw new BeanInstantiationException(rowHandler.rowMapper(), ex.getMessage(), ex); } } } // if (rowMapper == null) { // Class<?> returnClassType = smd.getMethod().getReturnType(); Class<?> rowType = getRowType(smd); // BUGFIX: SingleColumnRowMapper ? Primitive Type if (rowType.isPrimitive()) { rowType = ClassUtils.primitiveToWrapper(rowType); } // ?(?2Map) if (TypeUtils.isColumnType(rowType)) { if (Map.class.isAssignableFrom(returnClassType)) { rowMapper = new MapEntryColumnRowMapper(smd, rowType); } else { rowMapper = new SingleColumnRowMapper(rowType); } } // Bean?????? else { if (rowType == Map.class) { rowMapper = new ColumnMapRowMapper(); } else if (rowType.isArray()) { rowMapper = new ArrayRowMapper(rowType); } else if ((rowType == List.class) || (rowType == Collection.class)) { rowMapper = new ListRowMapper(smd); } else if (rowType == Set.class) { rowMapper = new SetRowMapper(smd); } else { boolean checkColumns = (rowHandler == null) ? true : rowHandler.checkColumns(); boolean checkProperties = (rowHandler == null) ? false : rowHandler.checkProperties(); String key = rowType.getName() + "[checkColumns=" + checkColumns + "&checkProperties=" + checkProperties + "]"; rowMapper = rowMappers.get(key); if (rowMapper == null) { rowMapper = new BeanPropertyRowMapper(rowType, checkColumns, checkProperties); // jade's BeanPropertyRowMapper here rowMappers.put(key, rowMapper); } } // DAOMaprowMapper?Map.Entry if (Map.class.isAssignableFrom(returnClassType)) { rowMapper = new MapEntryRowMapper(smd, rowMapper); } } } // if (rowMapper instanceof StatementAware) { ((StatementAware) rowMapper).setStatementMetaData(smd); } if (logger.isInfoEnabled()) { logger.info("using rowMapper " + rowMapper + " for " + smd); } return rowMapper; }
From source file:adalid.core.programmers.AbstractJavaProgrammer.java
protected String javaLangLess(Class<?> type) { return type == null ? "Object" : type.isArray() ? javaLangLess(type.getComponentType()) + "[]" : StringUtils.removeStart(type.getName(), "java.lang."); }
From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java
/** * check if elementClass is iterable.// ww w .j a va 2 s . c o m * * @param elementClass class to check * @return true if iterable, otherwise false */ public static boolean isIterableOrMap(final Class<?> elementClass) { // TODO(nchalko) handle iterables everywhere this is called. return elementClass.isArray() || Iterable.class.isAssignableFrom(elementClass) || Map.class.isAssignableFrom(elementClass); }
From source file:com.ms.commons.summer.web.handler.DataBinderUtil.java
/** * ?// w w w .j a v a 2 s .c o m * * @param method * @param model * @param request * @param response * @param c * @return */ @SuppressWarnings("unchecked") public static Object[] getArgs(Method method, Map<String, Object> model, HttpServletRequest request, HttpServletResponse response, Class<?> c) { Class<?>[] paramTypes = method.getParameterTypes(); Object[] args = new Object[paramTypes.length]; Map<String, Object> argMap = new HashMap<String, Object>(args.length); Map<String, String> pathValues = null; PathPattern pathPattern = method.getAnnotation(PathPattern.class); if (pathPattern != null) { String path = request.getRequestURI(); int index = path.lastIndexOf('.'); if (index != -1) { path = path.substring(0, index); String[] patterns = pathPattern.patterns(); pathValues = getPathValues(patterns, path); } } MapBindingResult errors = new MapBindingResult(argMap, ""); ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); for (int i = 0; i < paramTypes.length; i++) { Class<?> paramType = paramTypes[i]; MethodParameter methodParam = new MethodParameter(method, i); methodParam.initParameterNameDiscovery(parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(methodParam, c.getClass()); String paramName = methodParam.getParameterName(); // map if (Map.class.isAssignableFrom(paramType)) { args[i] = model; } // HttpServletRequest else if (HttpServletRequest.class.isAssignableFrom(paramType)) { args[i] = request; } // HttpServletResponse else if (HttpServletResponse.class.isAssignableFrom(paramType)) { args[i] = response; } // HttpSession else if (HttpSession.class.isAssignableFrom(paramType)) { args[i] = request.getSession(); } // Errors else if (Errors.class.isAssignableFrom(paramType)) { args[i] = errors; } // MultipartFile else if (MultipartFile.class.isAssignableFrom(paramType)) { MultipartFile[] files = resolveMultipartFiles(request, errors, paramName); if (files != null && files.length > 0) { args[i] = files[0]; } } // MultipartFile[] else if (MultipartFile[].class.isAssignableFrom(paramType)) { args[i] = resolveMultipartFiles(request, errors, paramName); } else { // ?? if (BeanUtils.isSimpleProperty(paramType)) { SimpleTypeConverter converter = new SimpleTypeConverter(); Object value; // ? if (paramType.isArray()) { value = request.getParameterValues(paramName); } else { Object[] parameterAnnotations = methodParam.getParameterAnnotations(); value = null; if (parameterAnnotations != null && parameterAnnotations.length > 0) { if (pathValues != null && pathValues.size() > 0) { for (Object object : parameterAnnotations) { if (PathVariable.class.isInstance(object)) { PathVariable pv = (PathVariable) object; if (StringUtils.isEmpty(pv.value())) { value = pathValues.get(paramName); } else { value = pathValues.get(pv.value()); } break; } } } } else { value = request.getParameter(paramName); } } try { args[i] = converter.convertIfNecessary(value, paramType, methodParam); model.put(paramName, args[i]); } catch (TypeMismatchException e) { errors.addError(new FieldError(paramName, paramName, e.getMessage())); } } else { // ???POJO if (paramType.isArray()) { ObjectArrayDataBinder binder = new ObjectArrayDataBinder(paramType.getComponentType(), paramName); args[i] = binder.bind(request); model.put(paramName, args[i]); } else { Object bindObject = BeanUtils.instantiateClass(paramType); SummerServletRequestDataBinder binder = new SummerServletRequestDataBinder(bindObject, paramName); binder.bind(request); BindException be = new BindException(binder.getBindingResult()); List<FieldError> fieldErrors = be.getFieldErrors(); for (FieldError fieldError : fieldErrors) { errors.addError(fieldError); } args[i] = binder.getTarget(); model.put(paramName, args[i]); } } } } return args; }
From source file:org.kohsuke.github.Requester.java
private <T> T parse(Class<T> type, T instance) throws IOException { InputStreamReader r = null;/*w ww . j a va2 s . co m*/ int responseCode = -1; String responseMessage = null; try { responseCode = uc.getResponseCode(); responseMessage = uc.getResponseMessage(); if (responseCode == 304) { return null; // special case handling for 304 unmodified, as the content will be "" } if (responseCode == 204 && type != null && type.isArray()) { // no content return type.cast(Array.newInstance(type.getComponentType(), 0)); } r = new InputStreamReader(wrapStream(uc.getInputStream()), "UTF-8"); String data = IOUtils.toString(r); if (type != null) try { return MAPPER.readValue(data, type); } catch (JsonMappingException e) { throw (IOException) new IOException("Failed to deserialize " + data).initCause(e); } if (instance != null) return MAPPER.readerForUpdating(instance).<T>readValue(data); return null; } catch (FileNotFoundException e) { // java.net.URLConnection handles 404 exception has FileNotFoundException, don't wrap exception in HttpException // to preserve backward compatibility throw e; } catch (IOException e) { throw new HttpException(responseCode, responseMessage, uc.getURL(), e); } finally { IOUtils.closeQuietly(r); } }
From source file:de.pribluda.android.jsonmarshaller.JSONUnmarshaller.java
/** * TODO: provide support for nested JSON objects * TODO: provide support for embedded JSON Arrays * * @param jsonObject//from w w w.j a va2 s . c o m * @param beanToBeCreatedClass * @param <T> * @return * @throws IllegalAccessException * @throws InstantiationException * @throws JSONException * @throws NoSuchMethodException * @throws java.lang.reflect.InvocationTargetException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unmarshall(JSONObject jsonObject, Class<T> beanToBeCreatedClass) throws IllegalAccessException, InstantiationException, JSONException, NoSuchMethodException, InvocationTargetException { T value = beanToBeCreatedClass.getConstructor().newInstance(); Iterator keys = jsonObject.keys(); while (keys.hasNext()) { String key = (String) keys.next(); Object field = jsonObject.get(key); // capitalise to standard setter pattern String methodName = SETTER_PREFIX + key.substring(0, 1).toUpperCase() + key.substring(1); //System.err.println("method name:" + methodName); Method method = getCandidateMethod(beanToBeCreatedClass, methodName); if (method != null) { Class clazz = method.getParameterTypes()[0]; // discriminate based on type if (field.equals(JSONObject.NULL)) { method.invoke(value, clazz.cast(null)); } else if (field instanceof String) { // check if we're an enum if (clazz.isEnum()) { Object enm = clazz.getMethod("valueOf", String.class).invoke(null, field); try { beanToBeCreatedClass.getMethod(methodName, clazz).invoke(value, enm); continue; } catch (NoSuchMethodException e) { // that means there was no such method, proceed } } // string shall be used directly, either to set or as constructor parameter (if suitable) try { beanToBeCreatedClass.getMethod(methodName, String.class).invoke(value, field); continue; } catch (NoSuchMethodException e) { // that means there was no such method, proceed } // or maybe there is method with suitable parameter? if (clazz.isPrimitive() && primitves.get(clazz) != null) { clazz = primitves.get(clazz); } try { method.invoke(value, clazz.getConstructor(String.class).newInstance(field)); } catch (NoSuchMethodException nsme) { // we are failed here, but so what? be lenient } } // we are done with string else if (clazz.isArray() || clazz.isAssignableFrom(List.class)) { // JSON array corresponds either to array type, or to some collection if (field instanceof JSONObject) { JSONArray array = new JSONArray(); array.put(field); field = array; } // we are interested in arrays for now if (clazz.isArray()) { // populate field value from JSON Array Object fieldValue = populateRecursive(clazz, field); method.invoke(value, fieldValue); } else if (clazz.isAssignableFrom(List.class)) { try { Type type = method.getGenericParameterTypes()[0]; if (type instanceof ParameterizedType) { Type param = ((ParameterizedType) type).getActualTypeArguments()[0]; if (param instanceof Class) { Class c = (Class) param; // populate field value from JSON Array Object fieldValue = populateRecursiveList(clazz, c, field); method.invoke(value, fieldValue); } } } catch (Exception e) { // failed } } } else if (field instanceof JSONObject) { // JSON object means nested bean - process recursively method.invoke(value, unmarshall((JSONObject) field, clazz)); } else if (clazz.equals(Date.class)) { method.invoke(value, new Date((Long) field)); } else { // fallback here, types not yet processed will be // set directly ( if possible ) // TODO: guard this? for better leniency method.invoke(value, field); } } } return value; }
From source file:javadz.beanutils.locale.LocaleBeanUtilsBean.java
/** * Convert the specified value to the required type using the * specified conversion pattern./* w w w. jav a2 s . c o m*/ * * @param type The Java type of target property * @param index The indexed subscript value (if any) * @param value The value to be converted * @param pattern The conversion pattern * @return The converted value */ protected Object convert(Class type, int index, Object value, String pattern) { if (log.isTraceEnabled()) { log.trace("Converting value '" + value + "' to type:" + type); } Object newValue = null; if (type.isArray() && (index < 0)) { // Scalar value into array if (value instanceof String) { String[] values = new String[1]; values[0] = (String) value; newValue = getLocaleConvertUtils().convert(values, type, pattern); } else if (value instanceof String[]) { newValue = getLocaleConvertUtils().convert((String[]) value, type, pattern); } else { newValue = value; } } else if (type.isArray()) { // Indexed value into array if (value instanceof String) { newValue = getLocaleConvertUtils().convert((String) value, type.getComponentType(), pattern); } else if (value instanceof String[]) { newValue = getLocaleConvertUtils().convert(((String[]) value)[0], type.getComponentType(), pattern); } else { newValue = value; } } else { // Value into scalar if (value instanceof String) { newValue = getLocaleConvertUtils().convert((String) value, type, pattern); } else if (value instanceof String[]) { newValue = getLocaleConvertUtils().convert(((String[]) value)[0], type, pattern); } else { newValue = value; } } return newValue; }
From source file:com.glaf.core.util.ReflectUtils.java
private static Object getEmptyObject(Class<?> returnType, Map<Class<?>, Object> emptyInstances, int level) { if (level > 2) return null; if (returnType == null) { return null; } else if (returnType == boolean.class || returnType == Boolean.class) { return false; } else if (returnType == char.class || returnType == Character.class) { return '\0'; } else if (returnType == byte.class || returnType == Byte.class) { return (byte) 0; } else if (returnType == short.class || returnType == Short.class) { return (short) 0; } else if (returnType == int.class || returnType == Integer.class) { return 0; } else if (returnType == long.class || returnType == Long.class) { return 0L; } else if (returnType == float.class || returnType == Float.class) { return 0F; } else if (returnType == double.class || returnType == Double.class) { return 0D; } else if (returnType.isArray()) { return Array.newInstance(returnType.getComponentType(), 0); } else if (returnType.isAssignableFrom(ArrayList.class)) { return new java.util.ArrayList<Object>(0); } else if (returnType.isAssignableFrom(HashSet.class)) { return new HashSet<Object>(0); } else if (returnType.isAssignableFrom(HashMap.class)) { return new java.util.concurrent.ConcurrentHashMap<Object, Object>(0); } else if (String.class.equals(returnType)) { return ""; } else if (!returnType.isInterface()) { try {/* w ww .j a v a2 s. c o m*/ Object value = emptyInstances.get(returnType); if (value == null) { value = returnType.newInstance(); emptyInstances.put(returnType, value); } Class<?> cls = value.getClass(); while (cls != null && cls != Object.class) { Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { Object property = getEmptyObject(field.getType(), emptyInstances, level + 1); if (property != null) { try { if (!field.isAccessible()) { field.setAccessible(true); } field.set(value, property); } catch (Throwable e) { } } } cls = cls.getSuperclass(); } return value; } catch (Throwable e) { return null; } } else { return null; } }