Example #1
1
  /**
   * Return the correspondent type by checking the "assignability" of the class received as
   * parameter.
   *
   * @param iClass Class to check
   * @return OType instance if found, otherwise null
   */
  public static OType getTypeByClass(final Class<?> iClass) {
    if (iClass == null) return null;

    for (final OType type : TYPES)
      for (int i = 0; i < type.javaTypes.length; ++i) {
        if (type.javaTypes[i] == iClass) return type;
        if (type.javaTypes[i] == Array.class && iClass.isArray()) return type;
      }

    int priority = 0;
    boolean comparedAtLeastOnce;
    do {
      comparedAtLeastOnce = false;
      for (final OType type : TYPES) {
        if (type.allowAssignmentFrom.length > priority) {
          if (type.allowAssignmentFrom[priority].isAssignableFrom(iClass)) return type;
          if (type.allowAssignmentFrom[priority].isArray() && iClass.isArray()) return type;
          comparedAtLeastOnce = true;
        }
      }

      priority++;
    } while (comparedAtLeastOnce);

    return null;
  }
Example #2
1
 /**
  * Appends the specified class name to the buffer. The class may represent a simple type, a
  * reference type or an array type.
  *
  * @param sb buffer
  * @param obj the class which name should be appended to the buffer
  * @throws NullPointerException if any of the arguments is null
  */
 void appendArrayType(StringBuilder sb, Class<?> obj) {
   if (!obj.isArray()) {
     sb.append(obj.getName());
     return;
   }
   int dimensions = 1;
   Class simplified = obj.getComponentType();
   obj = simplified;
   while (simplified.isArray()) {
     obj = simplified;
     dimensions++;
   }
   sb.append(obj.getName());
   switch (dimensions) {
     case 1:
       sb.append(DIMENSION_1);
       break;
     case 2:
       sb.append(DIMENSION_2);
       break;
     case 3:
       sb.append(DIMENSION_3);
       break;
     default:
       for (; dimensions > 0; dimensions--) {
         sb.append(DIMENSION_1);
       }
   }
 }
Example #3
1
 static String javaSignature(Class<?> type) {
   if (!type.isArray()) {
     return type.getName();
   } else {
     int arrayDimension = 0;
     do {
       ++arrayDimension;
       type = type.getComponentType();
     } while (type.isArray());
     String name = type.getName();
     String suffix = "[]";
     if (arrayDimension == 1) {
       return name.concat(suffix);
     } else {
       int length = name.length() + arrayDimension * suffix.length();
       StringBuffer sb = new StringBuffer(length);
       sb.append(name);
       while (arrayDimension != 0) {
         --arrayDimension;
         sb.append(suffix);
       }
       return sb.toString();
     }
   }
 }
Example #4
1
 private Object newValue(Class<?> type, String name) {
   try {
     if (type.isArray()) {
       Class<?> componentType = type.getComponentType();
       // TODO - only handles 2-dimensional arrays
       if (componentType.isArray()) {
         Object array = Array.newInstance(componentType, 1);
         Array.set(array, 0, Array.newInstance(componentType.getComponentType(), 0));
         return array;
       } else {
         return Array.newInstance(componentType, 0);
       }
     } else if (Collection.class.isAssignableFrom(type)) {
       return CollectionFactory.createCollection(type, 16);
     } else if (Map.class.isAssignableFrom(type)) {
       return CollectionFactory.createMap(type, 16);
     } else {
       return type.newInstance();
     }
   } catch (Exception ex) {
     // TODO Root cause exception context is lost here... should we throw another exception type
     // that preserves context instead?
     throw new NullValueInNestedPathException(
         getRootClass(),
         this.nestedPath + name,
         "Could not instantiate property type ["
             + type.getName()
             + "] to auto-grow nested property path: "
             + ex);
   }
 }
Example #5
1
 private Object newInstance(Class type) {
   try {
     return type.newInstance();
   } catch (Exception ex) {
     try {
       // Try a private constructor.
       Constructor constructor = type.getDeclaredConstructor();
       constructor.setAccessible(true);
       return constructor.newInstance();
     } catch (SecurityException ignored) {
     } catch (NoSuchMethodException ignored) {
       if (type.isArray())
         throw new SerializationException(
             "Encountered JSON object when expected array of type: " + type.getName(), ex);
       else if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers()))
         throw new SerializationException(
             "Class cannot be created (non-static member class): " + type.getName(), ex);
       else
         throw new SerializationException(
             "Class cannot be created (missing no-arg constructor): " + type.getName(), ex);
     } catch (Exception privateConstructorException) {
       ex = privateConstructorException;
     }
     throw new SerializationException(
         "Error constructing instance of class: " + type.getName(), ex);
   }
 }
Example #6
0
 /**
  * Look up and return any registered {@link Converter} for the specified source and destination
  * class; if there is no registered Converter, return <code>null</code>.
  *
  * @param sourceType Class of the value being converted
  * @param targetType Class of the value to be converted to
  * @return The registered {@link Converter} or <code>null</code> if not found
  */
 public Converter lookup(final Class<?> sourceType, final Class<?> targetType) {
   if (targetType == null) {
     throw new IllegalArgumentException("Target type is missing");
   }
   if (sourceType == null) {
     return this.lookup(targetType);
   }
   Converter converter = null;
   // Convert --> String
   if (targetType == String.class) {
     converter = this.lookup(sourceType);
     if (converter == null
         && (sourceType.isArray() || Collection.class.isAssignableFrom(sourceType))) {
       converter = this.lookup(String[].class);
     }
     if (converter == null) {
       converter = this.lookup(String.class);
     }
     return converter;
   }
   // Convert --> String array
   if (targetType == String[].class) {
     if (sourceType.isArray() || Collection.class.isAssignableFrom(sourceType)) {
       converter = this.lookup(sourceType);
     }
     if (converter == null) {
       converter = this.lookup(String[].class);
     }
     return converter;
   }
   return this.lookup(targetType);
 }
Example #7
0
 private boolean parametersMatchParameterList(Class<?>[] prmTypes, String[][] parameters) {
   int ndx = 0;
   while (ndx < prmTypes.length) {
     Class<?> prmType = prmTypes[ndx];
     if (ndx >= parameters.length) {
       return ndx == prmTypes.length - 1 && prmType.isArray();
     }
     if (ndx == prmTypes.length - 1
         && prmType.isArray()) { // Assume this only occurs for functions with var args
       Class<?> varArgClass = prmType.getComponentType();
       while (ndx < parameters.length) {
         Class<?> prmClass = resolver.resolveClass(parameters[ndx][0]);
         if (!varArgClass.isAssignableFrom(prmClass)) {
           return false;
         }
         ndx++;
       }
     } else {
       Class<?> prmClass = resolver.resolveClass(parameters[ndx][0]);
       if (!prmTypes[ndx].isAssignableFrom(prmClass)) {
         return false;
       }
     }
     ndx++;
   }
   return true;
 }
  public ExprNode validate(ExprValidationContext validationContext) throws ExprValidationException {
    // Must have 2 child nodes
    if (this.getChildNodes().length < 1) {
      throw new IllegalStateException("Group relational op node must have 1 or more parameters");
    }
    evaluators = ExprNodeUtility.getEvaluators(this.getChildNodes());

    Class typeOne = JavaClassHelper.getBoxedType(evaluators[0].getType());

    // collections, array or map not supported
    if ((typeOne.isArray())
        || (JavaClassHelper.isImplementsInterface(typeOne, Collection.class))
        || (JavaClassHelper.isImplementsInterface(typeOne, Map.class))) {
      throw new ExprValidationException(
          "Collection or array comparison is not allowed for the IN, ANY, SOME or ALL keywords");
    }

    List<Class> comparedTypes = new ArrayList<Class>();
    comparedTypes.add(typeOne);
    hasCollectionOrArray = false;
    for (int i = 0; i < this.getChildNodes().length - 1; i++) {
      Class propType = evaluators[i + 1].getType();
      if (propType.isArray()) {
        hasCollectionOrArray = true;
        if (propType.getComponentType() != Object.class) {
          comparedTypes.add(propType.getComponentType());
        }
      } else if (JavaClassHelper.isImplementsInterface(propType, Collection.class)) {
        hasCollectionOrArray = true;
      } else if (JavaClassHelper.isImplementsInterface(propType, Map.class)) {
        hasCollectionOrArray = true;
      } else {
        comparedTypes.add(propType);
      }
    }

    // Determine common denominator type
    Class coercionType;
    try {
      coercionType =
          JavaClassHelper.getCommonCoercionType(
              comparedTypes.toArray(new Class[comparedTypes.size()]));
    } catch (CoercionException ex) {
      throw new ExprValidationException("Implicit conversion not allowed: " + ex.getMessage());
    }

    // Must be either numeric or string
    if (coercionType != String.class) {
      if (!JavaClassHelper.isNumeric(coercionType)) {
        throw new ExprValidationException(
            "Implicit conversion from datatype '"
                + coercionType.getSimpleName()
                + "' to numeric is not allowed");
      }
    }

    computer = relationalOpEnum.getComputer(coercionType, coercionType, coercionType);
    return null;
  }
  /**
   * Transform an primitive array to an object array.
   *
   * @param arr the array.
   * @return an array.
   */
  private static Object toArray(Object arr) {

    if (arr == null) {
      return arr;
    }

    Class cls = arr.getClass();
    if (!cls.isArray()) {
      return arr;
    }

    Class compType = cls.getComponentType();
    int dim = 1;
    while (!compType.isPrimitive()) {
      if (!compType.isArray()) {
        return arr;
      } else {
        dim++;
        compType = compType.getComponentType();
      }
    }

    int[] length = new int[dim];
    length[0] = Array.getLength(arr);
    Object[] newarr = null;

    try {
      if (compType.equals(Integer.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Integer"), length);
      } else if (compType.equals(Double.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Double"), length);
      } else if (compType.equals(Long.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Long"), length);
      } else if (compType.equals(Float.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Float"), length);
      } else if (compType.equals(Short.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Short"), length);
      } else if (compType.equals(Byte.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Byte"), length);
      } else if (compType.equals(Character.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Character"), length);
      } else if (compType.equals(Boolean.TYPE)) {
        newarr = (Object[]) Array.newInstance(Class.forName("java.lang.Boolean"), length);
      }
    } catch (ClassNotFoundException ex) {
      System.out.println(ex);
    }

    for (int i = 0; i < length[0]; i++) {
      if (dim != 1) {
        newarr[i] = toArray(Array.get(arr, i));
      } else {
        newarr[i] = Array.get(arr, i);
      }
    }
    return newarr;
  }
  @Override
  public Object doInPreparedStatement(PreparedStatement ps)
      throws SQLException, DataAccessException {

    if (setter != null) {
      setter.setValues(ps);
    }

    int updated = ps.executeUpdate();
    if (updated == 0) {
      if (returnType.isArray()) {
        return Array.newInstance(wrappedIdType, 0);
      } else {
        return defaultValueOf(wrappedIdType);
      }
    }

    ResultSet keys = ps.getGeneratedKeys();
    if (keys != null) {
      try {
        Object ret = null;
        if (returnType.isArray()) {
          keys.last();
          int length = keys.getRow();
          keys.beforeFirst();
          ret = Array.newInstance(wrappedIdType, length);
        }

        for (int i = 0; keys.next(); i++) {
          Object value = mapper.mapRow(keys, i);
          if (value == null && idType.isPrimitive()) {
            // 如果本不是primitive的,保持null的语义不变
            value = defaultValueOf(wrappedIdType);
          }
          if (ret != null) {
            Array.set(ret, i + 1, value);
          } else {
            ret = value;
            break;
          }
        }
        return ret;
      } finally {
        JdbcUtils.closeResultSet(keys);
      }
    } else {
      if (returnType.isArray()) {
        return Array.newInstance(wrappedIdType, 0);
      } else {
        return defaultValueOf(wrappedIdType);
      }
    }
  }
Example #11
0
 protected static boolean sameArray(Object a, Object b) {
   Class<?> acls = a.getClass();
   Class<?> bcls = b.getClass();
   if (!acls.isArray() || !bcls.isArray() || Array.getLength(a) != Array.getLength(b)) {
     return false;
   }
   for (int i = 0; i < Array.getLength(a); i++) {
     if (!same(Array.get(a, i), Array.get(b, i))) {
       return false;
     }
   }
   return true;
 }
Example #12
0
 private static String getQualifiedName(Class<?> clazz) {
   if (clazz.isArray()) {
     return getQualifiedNameForArray(clazz);
   } else {
     return clazz.getName();
   }
 }
 private Object convertFromRuby(IRubyObject rubyResult, Class returnType) {
   Object result = JavaEmbedUtils.rubyToJava(this.ruby, rubyResult, returnType);
   if (result instanceof RubyArray && returnType.isArray()) {
     result = convertFromRubyArray(((RubyArray) result).toJavaArray(), returnType);
   }
   return result;
 }
Example #14
0
  public static long[] getLongValues(Object value, long[] defaultValue) {
    Class<?> clazz = value.getClass();

    if (clazz.isArray()) {
      Class<?> componentType = clazz.getComponentType();

      if (componentType.isAssignableFrom(String.class)) {
        return getLongValues((String[]) value, defaultValue);
      } else if (componentType.isAssignableFrom(Long.class)) {
        return (long[]) value;
      } else if (Number.class.isAssignableFrom(componentType)) {
        Number[] numbers = (Number[]) value;

        long[] values = new long[numbers.length];

        for (int i = 0; i < values.length; i++) {
          values[i] = numbers[i].longValue();
        }

        return values;
      }
    }

    return defaultValue;
  }
 private Object sample(Class<?> type) {
   if (type.isPrimitive()) {
     if (type == long.class) {
       return random.nextLong();
     }
     if (type == boolean.class) {
       return random.nextBoolean();
     }
   } else if (type.isEnum()) {
     Object[] candidates = type.getEnumConstants();
     return candidates[random.nextInt(candidates.length)];
   } else if (!type.isArray()) {
     if (type == String.class) {
       StringBuilder result = new StringBuilder();
       for (int len = 5 + random.nextInt(10); len > 0; len--) {
         result.append('a' + random.nextInt('z' - 'a'));
       }
       return result.toString();
     }
     if (type == Long.class) {
       return random.nextLong();
     }
     return mock(type);
   }
   throw new UnsupportedOperationException(
       "doesn't support " + type + " please add support for it.");
 }
 /** Method used by {@link TypeParser} when generics-aware version is constructed. */
 protected JavaType _fromParameterizedClass(Class<?> clz, List<JavaType> paramTypes) {
   if (clz.isArray()) { // ignore generics (should never have any)
     return ArrayType.construct(_fromType(clz.getComponentType(), null));
   }
   if (clz.isEnum()) { // ditto for enums
     return new SimpleType(clz);
   }
   if (Map.class.isAssignableFrom(clz)) {
     // First: if we do have param types, use them
     JavaType keyType, contentType;
     if (paramTypes.size() > 0) {
       keyType = paramTypes.get(0);
       contentType = (paramTypes.size() >= 2) ? paramTypes.get(1) : _unknownType();
       return MapType.construct(clz, keyType, contentType);
     }
     return _mapType(clz);
   }
   if (Collection.class.isAssignableFrom(clz)) {
     if (paramTypes.size() >= 1) {
       return CollectionType.construct(clz, paramTypes.get(0));
     }
     return _collectionType(clz);
   }
   if (paramTypes.size() == 0) {
     return new SimpleType(clz);
   }
   JavaType[] pt = paramTypes.toArray(new JavaType[paramTypes.size()]);
   return _constructSimple(clz, pt);
 }
 /**
  * Extension point to setBasicInfoForCreate the model attribute if not found in the model. The
  * default implementation uses the default constructor.
  *
  * @param attributeName the name of the attribute, never {@code null}
  * @param parameter the method parameter
  * @param binderFactory for creating WebDataBinder instance
  * @param request the current request
  * @return the created model attribute, never {@code null}
  */
 protected Object createAttribute(
     String attributeName,
     MethodParameter parameter,
     WebDataBinderFactory binderFactory,
     NativeWebRequest request)
     throws Exception {
   String value = getRequestValueForAttribute(attributeName, request);
   if (value != null) {
     Object attribute =
         createAttributeFromRequestValue(value, attributeName, parameter, binderFactory, request);
     if (attribute != null) {
       return attribute;
     }
   }
   Class<?> parameterType = parameter.getParameterType();
   if (parameterType.isArray() || List.class.isAssignableFrom(parameterType)) {
     return ArrayList.class.newInstance();
   }
   if (Set.class.isAssignableFrom(parameterType)) {
     return HashSet.class.newInstance();
   }
   if (MapWapper.class.isAssignableFrom(parameterType)) {
     return MapWapper.class.newInstance();
   }
   return BeanUtils.instantiateClass(parameter.getParameterType());
 }
Example #18
0
 /** @return if the class represents an array of immutable values. */
 private boolean isArrayOfImmutableTypes(Class<?> clazz) {
   if (!clazz.isArray()) {
     return false;
   }
   Class<?> component = clazz.getComponentType();
   return component.isPrimitive() || isImmutable(component);
 }
Example #19
0
  /**
   * Returns the component types of the given type. Returns <code>null</code> if given type does not
   * have a single component type. For example the following types all have the component-type
   * MyClass:
   *
   * <ul>
   *   <li>MyClass[]
   *   <li>List&lt;MyClass&gt;
   *   <li>Foo&lt;? extends MyClass&gt;
   *   <li>Bar&lt;? super MyClass&gt;
   *   <li>&lt;T extends MyClass&gt; T[]
   * </ul>
   */
  public static Class[] getComponentTypes(Type type, Class implClass) {
    if (type instanceof Class) {
      Class clazz = (Class) type;
      if (clazz.isArray()) {
        return new Class[] {clazz.getComponentType()};
      }
    } else if (type instanceof ParameterizedType) {
      ParameterizedType pt = (ParameterizedType) type;

      Type[] generics = pt.getActualTypeArguments();

      if (generics.length == 0) {
        return null;
      }

      Class[] types = new Class[generics.length];

      for (int i = 0; i < generics.length; i++) {
        types[i] = getRawType(generics[i], implClass);
      }
      return types;
    } else if (type instanceof GenericArrayType) {
      GenericArrayType gat = (GenericArrayType) type;

      Class rawType = getRawType(gat.getGenericComponentType(), implClass);
      if (rawType == null) {
        return null;
      }

      return new Class[] {rawType};
    }
    return null;
  }
Example #20
0
 public TypeWrapper(Class c) throws IntrospectionException {
   Map<String, Field> fields = new HashMap();
   loadFields(c, fields);
   BeanInfo bi = Introspector.getBeanInfo(c, Object.class);
   PropertyDescriptor[] props = bi.getPropertyDescriptors();
   for (int i = 0; i < props.length; i++) {
     PropertyDescriptor pd = props[i];
     Annotation[] ann = null;
     Field f = fields.get(pd.getName());
     if (f != null) {
       f.getAnnotations();
     }
     Class type = pd.getPropertyType();
     boolean arrayFlag = type.isArray();
     PropertyInfo pi =
         new PropertyInfo(
             pd.getName(),
             ann,
             (arrayFlag ? type.getComponentType() : type),
             arrayFlag,
             pd.getReadMethod(),
             pd.getWriteMethod());
     this.properties.put(pi.getName(), pi);
   }
 }
 /**
  * Set the value of a parameter using an object; use the java.lang equivalent objects for integral
  * values.
  *
  * <p>The JDBC specification specifies a standard mapping from Java Object types to SQL types. The
  * given argument java object will be converted to the corresponding SQL type before being sent to
  * the database.
  *
  * <p>Note that this method may be used to pass datatabase specific abstract data types, by using
  * a Driver specific Java type.
  *
  * @param parameterIndex The first parameter is 1, the second is 2, ...
  * @param x The object containing the input parameter value
  * @exception SQLException if a database-access error occurs.
  */
 public void setObject(int parameterIndex, Object x) throws SQLException {
   if (x == null) {
     setNull(parameterIndex, java.sql.Types.VARCHAR);
   } else if (x instanceof java.lang.String) {
     setString(parameterIndex, (String) x);
   } else if (x instanceof java.math.BigDecimal) {
     setBigDecimal(parameterIndex, (BigDecimal) x);
   } else if (x instanceof java.lang.Integer) {
     setInt(parameterIndex, ((Number) x).intValue());
   } else if (x instanceof java.lang.Long) {
     setLong(parameterIndex, ((Number) x).longValue());
   } else if (x instanceof java.lang.Byte) {
     setByte(parameterIndex, ((Number) x).byteValue());
   } else if (x instanceof java.lang.Short) {
     setShort(parameterIndex, ((Number) x).shortValue());
   } else if (x instanceof java.lang.Boolean) {
     setBoolean(parameterIndex, ((Boolean) x).booleanValue());
   } else if (x instanceof java.lang.Double) {
     setDouble(parameterIndex, ((Number) x).doubleValue());
   } else if (x instanceof java.lang.Float) {
     setFloat(parameterIndex, ((Number) x).floatValue());
   } else if (x instanceof java.sql.Date) {
     setDate(parameterIndex, (java.sql.Date) x);
   } else if (x instanceof java.util.Date) {
     setTimestamp(parameterIndex, new Timestamp(((java.util.Date) x).getTime()));
   } else {
     Class c = x.getClass();
     if (c.isArray() && c.getComponentType().equals(byte.class)) {
       setBytes(parameterIndex, (byte[]) x);
     } else {
       throw new SQLException("Not implemented");
     }
   }
 }
Example #22
0
  private static String printTypeName(Class<?> type) {
    // Primitives
    //
    if (type.equals(Integer.TYPE)) {
      return "int";
    } else if (type.equals(Long.TYPE)) {
      return "long";
    } else if (type.equals(Short.TYPE)) {
      return "short";
    } else if (type.equals(Byte.TYPE)) {
      return "byte";
    } else if (type.equals(Character.TYPE)) {
      return "char";
    } else if (type.equals(Boolean.TYPE)) {
      return "boolean";
    } else if (type.equals(Float.TYPE)) {
      return "float";
    } else if (type.equals(Double.TYPE)) {
      return "double";
    }

    // Arrays
    //
    if (type.isArray()) {
      Class<?> componentType = type.getComponentType();
      return printTypeName(componentType) + "[]";
    }

    // Everything else
    //
    return type.getName().replace('$', '.');
  }
Example #23
0
  /**
   * check whether a class should not be considered for transformation
   *
   * @param clazz the class to check
   * @return true if clazz should not be considered for transformation otherwise false
   */
  protected boolean isSkipClass(Class<?> clazz) {
    if (!inst.isModifiableClass(clazz)) {
      return true;
    }

    // we can safely skip array classes, interfaces and primitive classes

    if (clazz.isArray()) {
      return true;
    }

    if (clazz.isInterface()) {
      return true;
    }

    if (clazz.isPrimitive()) {
      return true;
    }

    String name = clazz.getName();

    if (isBytemanClass(name) || !isTransformable(name)) {
      return true;
    }

    return false;
  }
Example #24
0
 private static String format(Object value) {
   if (value == null) {
     return "null";
   }
   Class<? extends Object> type = value.getClass();
   if (type.isArray()) {
     StringBuilder builder = new StringBuilder();
     builder.append('{');
     int length = Array.getLength(value);
     for (int i = 0; i < length; i++) {
       if (i > 0) {
         builder.append(',');
       }
       builder.append(format(Array.get(value, i)));
     }
     builder.append('}');
     return builder.toString();
   } else if (EnumeratedParameter.class.isAssignableFrom(type)) {
     return ((EnumeratedParameter) value).getName();
   } else if (Interpolation.class.isAssignableFrom(type)) {
     if (Interpolation.getInstance(Interpolation.INTERP_NEAREST).equals(value)) {
       return "INTERP_NEAREST";
     } else if (Interpolation.getInstance(Interpolation.INTERP_BILINEAR).equals(value)) {
       return "INTERP_BILINEAR";
     } else if (Interpolation.getInstance(Interpolation.INTERP_BICUBIC).equals(value)) {
       return "INTERP_BICUBIC";
     } else if (Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2).equals(value)) {
       return "INTERP_BICUBIC_2";
     }
   } else if (CharSequence.class.isAssignableFrom(type)) {
     return "\"" + String.valueOf(value) + "\"";
   }
   return String.valueOf(value);
 }
Example #25
0
  /** Try and convert an object to a List. */
  private List<?> toList(Object o) {
    Class<?> c = o.getClass();
    if (!c.isArray()) {
      return null;
    }

    if (c.getComponentType().isPrimitive()) {
      if (o instanceof boolean[]) {
        return Arrays.asList(ArrayUtils.toObject((boolean[]) o));
      } else if (o instanceof byte[]) {
        return Arrays.asList(ArrayUtils.toObject((byte[]) o));
      } else if (o instanceof short[]) {
        return Arrays.asList(ArrayUtils.toObject((short[]) o));
      } else if (o instanceof int[]) {
        return Arrays.asList(ArrayUtils.toObject((int[]) o));
      } else if (o instanceof long[]) {
        return Arrays.asList(ArrayUtils.toObject((long[]) o));
      } else if (o instanceof float[]) {
        return Arrays.asList(ArrayUtils.toObject((float[]) o));
      } else if (o instanceof double[]) {
        return Arrays.asList(ArrayUtils.toObject((double[]) o));
      } else if (o instanceof char[]) {
        return Arrays.asList(ArrayUtils.toObject((char[]) o));
      } else {
        throw new RuntimeException("Unhandled primitive type");
      }
    } else {
      return Arrays.asList((Object[]) o);
    }
  }
  private static Deserializer getDeserializer(Class<?> clazz, Type type) {

    Deserializer deserializer;

    if (PrimitiveTypeUtils.isPrimitiveClass(clazz)) {
      deserializer = new PrimitiveTypeDeserializer();
    } else if (clazz.isEnum()) {
      deserializer = new EnumDeserializer(clazz);
    } else if (clazz.isArray()) {
      deserializer = ArrayDeserializer.INSTANCE;
    } else if (clazz == Set.class
        || clazz == HashSet.class
        || clazz == Collection.class
        || clazz == List.class
        || clazz == ArrayList.class) {
      deserializer = CollectionDeserializer.INSTANCE;
    } else if (Collection.class.isAssignableFrom(clazz)) {
      deserializer = CollectionDeserializer.INSTANCE;
    } else if (Map.class.isAssignableFrom(clazz)) {
      deserializer = MapDeserializer.INSTANCE;
    } else {
      deserializer = new JavaBeanDeserializer(clazz);
    }

    deserializerMap.put(type, deserializer);

    return deserializer;
  }
Example #27
0
 /**
  * 判断类型是否是Bean
  *
  * @param c
  * @return
  */
 public static boolean isBean(Class c) {
   return !isSupport(c)
       && !c.isArray()
       && !Collection.class.isAssignableFrom(c)
       && !Map.class.isAssignableFrom(c)
       && !Enum.class.isAssignableFrom(c);
 }
Example #28
0
  @SuppressWarnings("unchecked")
  private Object toValue(Object bean, Field field, XMLNode node) throws Exception {
    Class<?> type = field.getType();

    field.setAccessible(true);
    Object current = field.get(bean);
    if (current != null) type = current.getClass();

    if (Collection.class.isAssignableFrom(type)) {
      Type eleParamType = Object.class;
      ParameterizedType paramType = (ParameterizedType) field.getGenericType();
      if (paramType.getActualTypeArguments().length > 0) {
        eleParamType = paramType.getActualTypeArguments()[0];
      }
      Object[] array = (Object[]) toArrayValues((Class<?>) eleParamType, node);
      Collection collection = null;

      if (current != null && current instanceof Collection) {
        collection = (Collection) current;
      } else if (type.isInterface()) {
        collection = new ArrayList<Object>();
      } else {
        collection = (Collection) type.newInstance();
      }
      Collections.addAll(collection, array);
      return collection;
    }

    if (type.isArray()) return toArrayValues(type, node);

    return toValue(type, node);
  }
Example #29
0
 private Type getType(Class cls) {
   Type type = null;
   if (cls.isPrimitive() || Number.class.isAssignableFrom(cls)) {
     type = Type.PRIMITIVE;
   } else if (Character.class.isAssignableFrom(cls)) {
     type = Type.CHAR;
   } else if (String.class.isAssignableFrom(cls)) {
     type = Type.STRING;
   } else if (Date.class.isAssignableFrom(cls)) {
     type = Type.DATE;
   } else if (Calendar.class.isAssignableFrom(cls)) {
     type = Type.CALENDAR;
   } else if (BigInteger.class.isAssignableFrom(cls)) {
     type = Type.BIG_INTEGER;
   } else if (BigDecimal.class.isAssignableFrom(cls)) {
     type = Type.BIG_DECIMAL;
   } else if (cls.isArray()) {
     type = Type.ARRAY;
   } else if (Map.class.isAssignableFrom(cls)) {
     type = Type.MAP;
   } else if (Collection.class.isAssignableFrom(cls)) {
     type = Type.COLLECTION;
   } else {
     type = Type.OBJECT;
   }
   return type;
 }
  /** Create a named field with the specified type. */
  ObjectStreamField(String n, Class<?> clazz) {
    name = n;
    this.clazz = clazz;

    // Compute the typecode for easy switching
    if (clazz.isPrimitive()) {
      if (clazz == Integer.TYPE) {
        type = 'I';
      } else if (clazz == Byte.TYPE) {
        type = 'B';
      } else if (clazz == Long.TYPE) {
        type = 'J';
      } else if (clazz == Float.TYPE) {
        type = 'F';
      } else if (clazz == Double.TYPE) {
        type = 'D';
      } else if (clazz == Short.TYPE) {
        type = 'S';
      } else if (clazz == Character.TYPE) {
        type = 'C';
      } else if (clazz == Boolean.TYPE) {
        type = 'Z';
      }
    } else if (clazz.isArray()) {
      type = '[';
      typeString = ObjectStreamClass.getSignature(clazz);
    } else {
      type = 'L';
      typeString = ObjectStreamClass.getSignature(clazz);
    }

    if (typeString != null) signature = typeString;
    else signature = String.valueOf(type);
  }