List of usage examples for java.lang Class isPrimitive
@HotSpotIntrinsicCandidate public native boolean isPrimitive();
From source file:com.icesoft.faces.renderkit.dom_html_basic.MenuRenderer.java
protected Object convertArray(FacesContext facesContext, UISelectMany uiSelectMany, Class componentType, String[] newSubmittedValues) throws ConverterException { // component type of String means no conversion is necessary if (componentType.equals(String.class)) { return newSubmittedValues; }//from w ww . ja v a 2s . c o m // if newSubmittedValue is null return zero-length array if (newSubmittedValues == null) { return Array.newInstance(componentType, 0); } // create the array with specified component length int numberOfValues = newSubmittedValues.length; Object convertedValues = Array.newInstance(componentType, numberOfValues); // Determine if a converter is explicitly registered with the component Converter converter = uiSelectMany.getConverter(); if (converter == null) { // Determine if there is a default converter for the class converter = getConverterForClass(componentType); } if (converter == null) { // we don't need to convert base Object types if (componentType.equals(Object.class)) { return newSubmittedValues; } else { throw new ConverterException("Converter is null"); } } for (int index = 0; index < numberOfValues; index++) { // convert the next element Object nextConvertedElement = converter.getAsObject(facesContext, uiSelectMany, newSubmittedValues[index]); if (!componentType.isPrimitive()) { Array.set(convertedValues, index, nextConvertedElement); } else if (componentType.equals(Boolean.TYPE)) { Array.setBoolean(convertedValues, index, ((Boolean) nextConvertedElement).booleanValue()); } else if (componentType.equals(Integer.TYPE)) { Array.setInt(convertedValues, index, ((Integer) nextConvertedElement).intValue()); } else if (componentType.equals(Long.TYPE)) { Array.setLong(convertedValues, index, ((Long) nextConvertedElement).longValue()); } else if (componentType.equals(Short.TYPE)) { Array.setShort(convertedValues, index, ((Short) nextConvertedElement).shortValue()); } else if (componentType.equals(Byte.TYPE)) { Array.setByte(convertedValues, index, ((Byte) nextConvertedElement).byteValue()); } else if (componentType.equals(Float.TYPE)) { Array.setFloat(convertedValues, index, ((Float) nextConvertedElement).floatValue()); } else if (componentType.equals(Double.TYPE)) { Array.setDouble(convertedValues, index, ((Double) nextConvertedElement).doubleValue()); } else if (componentType.equals(Character.TYPE)) { Array.setChar(convertedValues, index, ((Character) nextConvertedElement).charValue()); } } return convertedValues; }
From source file:fr.certu.chouette.command.Command.java
private void addAttribute(Object object, String attrname, String value) throws Exception { Class<?> beanClass = object.getClass(); Method adder = findAdder(beanClass, attrname); Class<?> type = adder.getParameterTypes()[0]; Object arg = null;//w w w . j a v a 2s .c om if (type.isEnum()) { arg = toEnum(type, value); } else if (type.isPrimitive()) { arg = toPrimitive(type, value); } else { arg = toObject(type, value); } adder.invoke(object, arg); }
From source file:com.googlecode.jsonrpc4j.JsonRpcServer.java
/** * Determines whether or not the given {@link JsonNode} matches * the given type. This method is limitted to a few java types * only and shouldn't be used to determine with great accuracy * whether or not the types match./*from w w w . j av a 2 s . co m*/ * * @param node the {@link JsonNode} * @param type the {@link Class} * @return true if the types match, false otherwise */ private boolean isMatchingType(JsonNode node, Class<?> type) { if (node.isNull()) { return true; } else if (node.isTextual()) { return String.class.isAssignableFrom(type); } else if (node.isNumber()) { return Number.class.isAssignableFrom(type) || short.class.isAssignableFrom(type) || int.class.isAssignableFrom(type) || long.class.isAssignableFrom(type) || float.class.isAssignableFrom(type) || double.class.isAssignableFrom(type); } else if (node.isArray() && type.isArray()) { return (node.size() > 0) ? isMatchingType(node.get(0), type.getComponentType()) : false; } else if (node.isArray()) { return type.isArray() || Collection.class.isAssignableFrom(type); } else if (node.isBinary()) { return byte[].class.isAssignableFrom(type) || Byte[].class.isAssignableFrom(type) || char[].class.isAssignableFrom(type) || Character[].class.isAssignableFrom(type); } else if (node.isBoolean()) { return boolean.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type); } else if (node.isObject() || node.isPojo()) { return !type.isPrimitive() && !String.class.isAssignableFrom(type) && !Number.class.isAssignableFrom(type) && !Boolean.class.isAssignableFrom(type); } // not sure if it's a matching type return false; }
From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java
private Properties createSettings(Class<?> clazz, String fn, String comment) { Properties props = new SortedProperties(); try {//from w ww . j av a 2 s . c o m // File file = new File("/" + DIR_PATH + "/" + fn); File file = new File(fn); Method[] methods = clazz.getMethods(); for (Method method : methods) { // Find setters if (method.getName().startsWith("set")) { if (method.isAnnotationPresent(Param.class)) { Annotation annotation = method.getAnnotation(Param.class); Param param = (Param) annotation; if (param.name().equals("") || param.values().length == 0) { throw new RuntimeException("Wrong param in class " + clazz.getCanonicalName() + " with method " + method.getName()); } Class<?>[] paramClazzes = method.getParameterTypes(); if (paramClazzes.length != 1) { throw new RuntimeException("Error contract design in class " + clazz.getCanonicalName() + " with method " + method.getName()); } // Check param belongs to List Class<?> paramClazz = paramClazzes[0]; if (List.class.isAssignableFrom(paramClazz)) { // Oh, its array... // May be its InetSocketAddress? Type[] gpt = method.getGenericParameterTypes(); if (gpt[0] instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) gpt[0]; Type[] typeArguments = type.getActualTypeArguments(); for (Type typeArgument : typeArguments) { Class<?> classType = ((Class<?>) typeArgument); if (InetSocketAddress.class.isAssignableFrom(classType)) { String[] vals = param.values(); for (int i = 0; i < vals.length / 2; ++i) { props.setProperty(param.name() + "." + String.valueOf(i) + ".ip", vals[i * 2]); props.setProperty(param.name() + "." + String.valueOf(i) + ".port", vals[i * 2 + 1]); } props.setProperty(param.name() + ".count", String.valueOf(vals.length / 2)); } else { throw new RuntimeException("Settings param in class " + clazz.getCanonicalName() + " with method " + method.getName() + " not implementes yet"); } } } } else if (paramClazz.isPrimitive()) { props.setProperty(param.name(), param.values()[0]); } else if (String.class.isAssignableFrom(paramClazz)) { props.setProperty(param.name(), param.values()[0]); } else { throw new RuntimeException("Settings param in class " + clazz.getCanonicalName() + " with method " + method.getName() + " not implemented yet"); } } } } BotUtils.saveProperties(file, props, comment); } catch (IOException e) { logger.error("Error save file " + fn); } return props; }
From source file:com.sun.faces.renderkit.html_basic.MenuRenderer.java
protected Object handleArrayCase(FacesContext context, UISelectMany uiSelectMany, Class arrayClass, String[] newValues) throws ConverterException { Object result = null;//w ww. ja va 2 s .c o m Class elementType = null; Converter converter = null; int i = 0, len = (null != newValues ? newValues.length : 0); elementType = arrayClass.getComponentType(); // Optimization: If the elementType is String, we don't need // conversion. Just return newValues. if (elementType.equals(String.class)) { return newValues; } try { result = Array.newInstance(elementType, len); } catch (Exception e) { throw new ConverterException(e); } // bail out now if we have no new values, returning our // oh-so-useful zero-length array. if (null == newValues) { return result; } // obtain a converter. // attached converter takes priority if (null == (converter = uiSelectMany.getConverter())) { // Otherwise, look for a by-type converter if (null == (converter = Util.getConverterForClass(elementType, context))) { // if that fails, and the attached values are of Object type, // we don't need conversion. if (elementType.equals(Object.class)) { return newValues; } String valueStr = ""; for (i = 0; i < newValues.length; i++) { valueStr = valueStr + " " + newValues[i]; } Object[] params = { valueStr, "null Converter" }; throw new ConverterException(Util.getExceptionMessage(Util.CONVERSION_ERROR_MESSAGE_ID, params)); } } Util.doAssert(null != result); if (elementType.isPrimitive()) { for (i = 0; i < len; i++) { if (elementType.equals(Boolean.TYPE)) { Array.setBoolean(result, i, ((Boolean) converter.getAsObject(context, uiSelectMany, newValues[i])).booleanValue()); } else if (elementType.equals(Byte.TYPE)) { Array.setByte(result, i, ((Byte) converter.getAsObject(context, uiSelectMany, newValues[i])).byteValue()); } else if (elementType.equals(Double.TYPE)) { Array.setDouble(result, i, ((Double) converter.getAsObject(context, uiSelectMany, newValues[i])).doubleValue()); } else if (elementType.equals(Float.TYPE)) { Array.setFloat(result, i, ((Float) converter.getAsObject(context, uiSelectMany, newValues[i])).floatValue()); } else if (elementType.equals(Integer.TYPE)) { Array.setInt(result, i, ((Integer) converter.getAsObject(context, uiSelectMany, newValues[i])).intValue()); } else if (elementType.equals(Character.TYPE)) { Array.setChar(result, i, ((Character) converter.getAsObject(context, uiSelectMany, newValues[i])).charValue()); } else if (elementType.equals(Short.TYPE)) { Array.setShort(result, i, ((Short) converter.getAsObject(context, uiSelectMany, newValues[i])).shortValue()); } else if (elementType.equals(Long.TYPE)) { Array.setLong(result, i, ((Long) converter.getAsObject(context, uiSelectMany, newValues[i])).longValue()); } } } else { for (i = 0; i < len; i++) { if (log.isDebugEnabled()) { Object converted = converter.getAsObject(context, uiSelectMany, newValues[i]); log.debug("String value: " + newValues[i] + " converts to : " + converted.toString()); } Array.set(result, i, converter.getAsObject(context, uiSelectMany, newValues[i])); } } return result; }
From source file:com.xwtec.xwserver.util.json.JSONObject.java
/** * Creates a bean from a JSONObject, with the specific configuration. *//*from w w w . j av a2 s. c o m*/ public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) { if (jsonObject == null || jsonObject.isNullObject() || root == null) { return root; } Class rootClass = root.getClass(); if (rootClass.isInterface()) { throw new JSONException("Root bean is an interface. " + rootClass); } Map classMap = jsonConfig.getClassMap(); if (classMap == null) { classMap = Collections.EMPTY_MAP; } Map props = JSONUtils.getProperties(jsonObject); PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter(); for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) { String name = (String) entries.next(); Class type = (Class) props.get(name); Object value = jsonObject.get(name); if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) { continue; } String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig); try { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key); if (pd != null && pd.getWriteMethod() == null) { log.info("Property '" + key + "' of " + root.getClass() + " has no write method. SKIPPED."); continue; } if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) { Class targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig); setProperty(root, key, list, jsonConfig); } else { Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType()); Class targetInnerType = findTargetClass(key, classMap); if (innerType.equals(Object.class) && targetInnerType != null && !targetInnerType.equals(Object.class)) { innerType = targetInnerType; } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null); Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig); if (innerType.isPrimitive() || JSONUtils.isNumber(innerType) || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) { array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } else if (!array.getClass().equals(pd.getPropertyType())) { if (!pd.getPropertyType().equals(Object.class)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(Array.newInstance(innerType, 0).getClass()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher( new BeanMorpher(innerType, JSONUtils.getMorpherRegistry())); JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher); } array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } } setProperty(root, key, array, jsonConfig); } } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (pd != null) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(root, key, null, jsonConfig); } else if (!pd.getPropertyType().isInstance(value)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(pd.getPropertyType()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { log.warn("Can't transform property '" + key + "' from " + type.getName() + " into " + pd.getPropertyType().getName() + ". Will register a default BeanMorpher"); JSONUtils.getMorpherRegistry().registerMorpher( new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry())); } setProperty(root, key, JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value), jsonConfig); } else { setProperty(root, key, value, jsonConfig); } } else if (root instanceof Map) { setProperty(root, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + root.getClass().getName()); } } else { if (pd != null) { Class targetClass = pd.getPropertyType(); if (jsonConfig.isHandleJettisonSingleElementArray()) { JSONArray array = new JSONArray().element(value, jsonConfig); Class newTargetClass = findTargetClass(key, classMap); newTargetClass = newTargetClass == null ? findTargetClass(name, classMap) : newTargetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass, null); if (targetClass.isArray()) { setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig), jsonConfig); } else if (Collection.class.isAssignableFrom(targetClass)) { setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig), jsonConfig); } else if (JSONArray.class.isAssignableFrom(targetClass)) { setProperty(root, key, array, jsonConfig); } else { setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else { if (targetClass == Object.class) { targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else if (root instanceof Map) { Class targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + rootClass.getName()); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(root, key, null, jsonConfig); } } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException("Error while setting property=" + name + " type " + type, e); } } return root; }
From source file:com.flexive.faces.renderer.FxSelectRenderer.java
/** * Convert select many values to given array class * * @param context faces context/* w w w. java 2 s . c o m*/ * @param uiSelectMany select many component * @param arrayClass the array class * @param newValues new values to convert * @return converted values * @throws ConverterException on errors */ protected Object convertSelectManyValues(FacesContext context, UISelectMany uiSelectMany, Class arrayClass, String[] newValues) throws ConverterException { Object result; Converter converter; int len = (null != newValues ? newValues.length : 0); Class elementType = arrayClass.getComponentType(); // Optimization: If the elementType is String, we don't need // conversion. Just return newValues. if (elementType.equals(String.class)) return newValues; try { result = Array.newInstance(elementType, len); } catch (Exception e) { throw new ConverterException(e); } // bail out now if we have no new values, returning our // oh-so-useful zero-length array. if (null == newValues) return result; // obtain a converter. // attached converter takes priority if (null == (converter = uiSelectMany.getConverter())) { // Otherwise, look for a by-type converter if (null == (converter = FxJsfComponentUtils.getConverterForClass(elementType, context))) { // if that fails, and the attached values are of Object type, // we don't need conversion. if (elementType.equals(Object.class)) return newValues; StringBuffer valueStr = new StringBuffer(); for (int i = 0; i < len; i++) { if (i == 0) valueStr.append(newValues[i]); else valueStr.append(' ').append(newValues[i]); } throw new ConverterException("Could not get a converter for " + String.valueOf(valueStr)); } } if (elementType.isPrimitive()) { for (int i = 0; i < len; i++) { if (elementType.equals(Boolean.TYPE)) { Array.setBoolean(result, i, ((Boolean) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Byte.TYPE)) { Array.setByte(result, i, ((Byte) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Double.TYPE)) { Array.setDouble(result, i, ((Double) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Float.TYPE)) { Array.setFloat(result, i, ((Float) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Integer.TYPE)) { Array.setInt(result, i, ((Integer) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Character.TYPE)) { Array.setChar(result, i, ((Character) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Short.TYPE)) { Array.setShort(result, i, ((Short) converter.getAsObject(context, uiSelectMany, newValues[i]))); } else if (elementType.equals(Long.TYPE)) { Array.setLong(result, i, ((Long) converter.getAsObject(context, uiSelectMany, newValues[i]))); } } } else { for (int i = 0; i < len; i++) Array.set(result, i, converter.getAsObject(context, uiSelectMany, newValues[i])); } return result; }
From source file:com.xwtec.xwserver.util.json.JSONObject.java
/** * Creates a JSONDynaBean from a JSONObject. *//*from w w w . ja v a 2s. c om*/ public static Object toBean(JSONObject jsonObject) { if (jsonObject == null || jsonObject.isNullObject()) { return null; } DynaBean dynaBean = null; JsonConfig jsonConfig = new JsonConfig(); Map props = JSONUtils.getProperties(jsonObject); dynaBean = JSONUtils.newDynaBean(jsonObject, jsonConfig); for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) { String name = (String) entries.next(); String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig); Class type = (Class) props.get(name); Object value = jsonObject.get(name); try { if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { dynaBean.set(key, JSONArray.toCollection((JSONArray) value)); } else if (String.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type) || JSONUtils.isNumber(type) || Character.class.isAssignableFrom(type) || JSONFunction.class.isAssignableFrom(type)) { dynaBean.set(key, value); } else { dynaBean.set(key, toBean((JSONObject) value)); } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); dynaBean.set(key, JSONUtils.getMorpherRegistry().morph(type, null)); } else { dynaBean.set(key, null); } } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException("Error while setting property=" + name + " type" + type, e); } } return dynaBean; }
From source file:net.sf.json.JSONObject.java
/** * Creates a bean from a JSONObject, with the specific configuration. *///w ww . j av a 2s . c om public static Object toBean(JSONObject jsonObject, Object root, JsonConfig jsonConfig) { if (jsonObject == null || jsonObject.isNullObject() || root == null) { return root; } Class rootClass = root.getClass(); if (rootClass.isInterface()) { throw new JSONException("Root bean is an interface. " + rootClass); } Map classMap = jsonConfig.getClassMap(); if (classMap == null) { classMap = Collections.EMPTY_MAP; } Map props = JSONUtils.getProperties(jsonObject); PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter(); for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) { String name = (String) entries.next(); Class type = (Class) props.get(name); Object value = jsonObject.get(name); if (javaPropertyFilter != null && javaPropertyFilter.apply(root, name, value)) { continue; } String key = JSONUtils.convertToJavaIdentifier(name, jsonConfig); try { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(root, key); if (pd != null && pd.getWriteMethod() == null) { log.info("Property '" + key + "' of " + root.getClass() + " has no write method. SKIPPED."); continue; } if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { if (pd == null || List.class.isAssignableFrom(pd.getPropertyType())) { Class targetClass = resolveClass(classMap, key, name, type); Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); List list = JSONArray.toList((JSONArray) value, newRoot, jsonConfig); setProperty(root, key, list, jsonConfig); } else { Class innerType = JSONUtils.getInnerComponentType(pd.getPropertyType()); Class targetInnerType = findTargetClass(key, classMap); if (innerType.equals(Object.class) && targetInnerType != null && !targetInnerType.equals(Object.class)) { innerType = targetInnerType; } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(innerType, null); Object array = JSONArray.toArray((JSONArray) value, newRoot, jsonConfig); if (innerType.isPrimitive() || JSONUtils.isNumber(innerType) || Boolean.class.isAssignableFrom(innerType) || JSONUtils.isString(innerType)) { array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } else if (!array.getClass().equals(pd.getPropertyType())) { if (!pd.getPropertyType().equals(Object.class)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(Array.newInstance(innerType, 0).getClass()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { ObjectArrayMorpher beanMorpher = new ObjectArrayMorpher( new BeanMorpher(innerType, JSONUtils.getMorpherRegistry())); JSONUtils.getMorpherRegistry().registerMorpher(beanMorpher); } array = JSONUtils.getMorpherRegistry() .morph(Array.newInstance(innerType, 0).getClass(), array); } } setProperty(root, key, array, jsonConfig); } } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (pd != null) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(root, key, null, jsonConfig); } else if (!pd.getPropertyType().isInstance(value)) { Morpher morpher = JSONUtils.getMorpherRegistry() .getMorpherFor(pd.getPropertyType()); if (IdentityObjectMorpher.getInstance().equals(morpher)) { log.warn("Can't transform property '" + key + "' from " + type.getName() + " into " + pd.getPropertyType().getName() + ". Will register a default BeanMorpher"); JSONUtils.getMorpherRegistry().registerMorpher( new BeanMorpher(pd.getPropertyType(), JSONUtils.getMorpherRegistry())); } setProperty(root, key, JSONUtils.getMorpherRegistry().morph(pd.getPropertyType(), value), jsonConfig); } else { setProperty(root, key, value, jsonConfig); } } else if (root instanceof Map) { setProperty(root, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + root.getClass().getName()); } } else { if (pd != null) { Class targetClass = pd.getPropertyType(); if (jsonConfig.isHandleJettisonSingleElementArray()) { JSONArray array = new JSONArray().element(value, jsonConfig); Class newTargetClass = resolveClass(classMap, key, name, type); Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(newTargetClass, (JSONObject) value); if (targetClass.isArray()) { setProperty(root, key, JSONArray.toArray(array, newRoot, jsonConfig), jsonConfig); } else if (Collection.class.isAssignableFrom(targetClass)) { setProperty(root, key, JSONArray.toList(array, newRoot, jsonConfig), jsonConfig); } else if (JSONArray.class.isAssignableFrom(targetClass)) { setProperty(root, key, array, jsonConfig); } else { setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else { if (targetClass == Object.class) { targetClass = resolveClass(classMap, key, name, type); if (targetClass == null) { targetClass = Object.class; } } Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, (JSONObject) value); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } } else if (root instanceof Map) { Class targetClass = findTargetClass(key, classMap); targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass; Object newRoot = jsonConfig.getNewBeanInstanceStrategy().newInstance(targetClass, null); setProperty(root, key, toBean((JSONObject) value, newRoot, jsonConfig), jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + rootClass.getName()); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(root, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(root, key, null, jsonConfig); } } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException("Error while setting property=" + name + " type " + type, e); } } return root; }
From source file:jp.co.acroquest.jsonic.JSON.java
/** * Converts Map, List, Number, String, Boolean or null to other Java Objects after parsing. * //from w w w . ja v a 2s . c om * @param context current context. * @param value null or the instance of Map, List, Number, String or Boolean. * @param cls class for converting * @param type generics type for converting. type equals to c if not generics. * @return a converted object * @throws Exception if conversion failed. */ @SuppressWarnings("unchecked") protected <T> T postparse(Context context, Object value, Class<? extends T> cls, Type type) throws Exception { Converter c = null; if (value == null) { if (!cls.isPrimitive()) { c = NullConverter.INSTANCE; } } else { JSONHint hint = context.getHint(); if (hint == null) { // no handle } else if (hint.serialized() && hint != context.skipHint) { c = FormatConverter.INSTANCE; } else if (Serializable.class.equals(hint.type())) { c = SerializableConverter.INSTANCE; } else if (String.class.equals(hint.type())) { c = StringSerializableConverter.INSTANCE; } } if (c == null) { if (value != null && cls.equals(type) && cls.isAssignableFrom(value.getClass())) { c = PlainConverter.INSTANCE; } else { c = CONVERT_MAP.get(cls); } } if (c == null) { if (context.hasMemberCache(cls)) { c = ObjectConverter.INSTANCE; } else if (Properties.class.isAssignableFrom(cls)) { c = PropertiesConverter.INSTANCE; } else if (Map.class.isAssignableFrom(cls)) { c = MapConverter.INSTANCE; } else if (Collection.class.isAssignableFrom(cls)) { c = CollectionConverter.INSTANCE; } else if (cls.isArray()) { c = ArrayConverter.INSTANCE; } else if (cls.isEnum()) { c = EnumConverter.INSTANCE; } else if (Date.class.isAssignableFrom(cls)) { c = DateConverter.INSTANCE; } else if (Calendar.class.isAssignableFrom(cls)) { c = CalendarConverter.INSTANCE; } else if (CharSequence.class.isAssignableFrom(cls)) { c = CharSequenceConverter.INSTANCE; } else if (Appendable.class.isAssignableFrom(cls)) { c = AppendableConverter.INSTANCE; } else if (cls.equals(ClassUtil.findClass("java.net.InetAddress"))) { c = InetAddressConverter.INSTANCE; } else if (java.sql.Array.class.isAssignableFrom(cls) || Struct.class.isAssignableFrom(cls)) { c = NullConverter.INSTANCE; } else { c = ObjectConverter.INSTANCE; } } if (c != null) { return (T) c.convert(this, context, value, cls, type); } else { throw new UnsupportedOperationException(); } }