示例#1
0
 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();
     }
   }
 }
示例#2
0
 public static boolean typesMatch(Class<?>[] usedTypes, Class<?>[] expectedTypes) {
   // expectedTypes is empty
   if (ArrayUtil.isEmpty(expectedTypes)) return ArrayUtil.isEmpty(usedTypes);
   Class<?> lastExpectedType = ArrayUtil.lastElementOf(expectedTypes);
   if (lastExpectedType.isArray()) {
     // process varargs parameter
     if (usedTypes.length < expectedTypes.length - 1) return false; // fault
     if (usedTypes.length == expectedTypes.length - 1)
       return typesMatch(
           usedTypes, ArrayUtil.copyOfRange(expectedTypes, 0, usedTypes.length)); // empty varargs
     // check if all used types match the varargs type
     if (usedTypes.length >= expectedTypes.length) {
       Class<?> componentType = lastExpectedType.getComponentType();
       for (int i = expectedTypes.length - 1; i < usedTypes.length; i++) {
         Class<?> foundType = usedTypes[i];
         if (!typeMatches(foundType, componentType)) return false;
       }
       return true;
     }
   }
   if (usedTypes.length != expectedTypes.length) return false;
   if (expectedTypes.length == 0 && usedTypes.length == 0) return true;
   for (int i = 0; i < usedTypes.length; i++) {
     Class<?> expectedType = expectedTypes[i];
     Class<?> foundType = usedTypes[i];
     if (!typeMatches(foundType, expectedType)) return false;
   }
   return true;
 }
  public void setCollectionType(Class<?> argumentType, Type genericType) {
    this.collectionArgumentType = argumentType;
    this.collectionGenericType = genericType;

    if (genericType instanceof ParameterizedType) {
      ParameterizedType parameterizedCollectionType = (ParameterizedType) genericType;
      this.collectionRawType = parameterizedCollectionType.getRawType();
      this.collectionElementType =
          (Class<?>) parameterizedCollectionType.getActualTypeArguments()[0];
    }

    if (argumentType.isArray()) {
      this.collectionKind = CollectionKind.ARRAY;
      this.collectionElementType = this.collectionArgumentType.getComponentType();
    } else if (FactoryUtil.isSubstitutableFor(argumentType, List.class)) {
      this.collectionKind = CollectionKind.LIST;
    } else if (FactoryUtil.isSubstitutableFor(argumentType, Set.class)) {
      this.collectionKind = CollectionKind.SET;
    } else if (FactoryUtil.isSubstitutableFor(argumentType, Collection.class)) {
      this.collectionKind = CollectionKind.LIST;
    }

    /*
     * todo move this code to wrapInConversionFactoryIfNecessary, if possible. Then the factory knows as little as
     * possible about parsing
     */
    FactoryBuilder builder = new FactoryBuilder();
    for (int i = 0; i < this.collectionContentFactories.size(); i++) {
      this.collectionContentFactories.set(
          i,
          builder.wrapInConversionFactoryIfNecessary(
              this.collectionContentFactories.get(i), this.collectionElementType));
    }
  }
示例#4
0
  public Class getPropertyType(BeanEventType eventType, EventAdapterService eventAdapterService) {
    Class result = null;

    for (Iterator<Property> it = properties.iterator(); it.hasNext(); ) {
      Property property = it.next();
      result = property.getPropertyType(eventType, eventAdapterService);

      if (result == null) {
        // property not found, return null
        return null;
      }

      if (it.hasNext()) {
        // Map cannot be used to further nest as the type cannot be determined
        if (result == Map.class) {
          return null;
        }

        if (result.isArray()
            || result.isPrimitive()
            || JavaClassHelper.isJavaBuiltinDataType(result)) {
          return null;
        }

        eventType =
            eventAdapterService
                .getBeanEventTypeFactory()
                .createBeanType(result.getName(), result, false, false, false);
      }
    }

    return result;
  }
示例#5
0
  /**
   * Assumes that all of the parents of c have been registered already.
   *
   * @param c
   */
  @SuppressWarnings("unchecked")
  private <T> Node registerClass(final Class<T> c) throws ClassHierarchyException {
    if (c.isArray()) {
      throw new UnsupportedOperationException("Can't register array types");
    }
    try {
      return getAlreadyBoundNode(c);
    } catch (final NameResolutionException e) {
      // node not bound yet
    }

    final Node n = buildPathToNode(c);

    if (n instanceof ClassNode) {
      final ClassNode<T> cn = (ClassNode<T>) n;
      final Class<T> superclass = (Class<T>) c.getSuperclass();
      if (superclass != null) {
        try {
          ((ClassNode<T>) getAlreadyBoundNode(superclass)).putImpl(cn);
        } catch (final NameResolutionException e) {
          throw new IllegalStateException(e);
        }
      }
      for (final Class<?> interf : c.getInterfaces()) {
        try {
          ((ClassNode<T>) getAlreadyBoundNode(interf)).putImpl(cn);
        } catch (final NameResolutionException e) {
          throw new IllegalStateException(e);
        }
      }
    }
    return n;
  }
示例#6
0
 private static Object parseValue(String value, Prop p, Class type) {
   Object v = value;
   if (type.isArray()) {
     StringTokenizer st = new StringTokenizer(value, ",");
     Class ctype = type.getComponentType();
     v = Array.newInstance(ctype, st.countTokens());
     for (int i = 0; st.hasMoreTokens(); i++)
       Array.set(v, i, parseValue(st.nextToken(), p, ctype));
   } else if (type == boolean.class) {
     v = Boolean.valueOf(value);
   } else if (type == double.class) {
     v = Double.valueOf(value);
   } else if (type == int.class) {
     v = Integer.valueOf(value);
   } else if (p.field.isAnnotationPresent(TimeIntervalProp.class)) {
     if (value.endsWith("s")) {
       v = (long) (Double.parseDouble(value.substring(0, value.length() - 1)) * SEC);
     } else if (value.endsWith("m")) {
       v = (long) (Double.parseDouble(value.substring(0, value.length() - 1)) * MIN);
     } else {
       v = Long.valueOf(value);
     }
   }
   return v;
 }
  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;
  }
  /**
   * Create a default object of the given type. Prefers constructors with as few arguments as
   * possible. Creates an empty proxy for interfaces.
   *
   * @param type type to instantiate
   * @return default instance
   * @throws Exception if the default instance could not be created
   */
  private static Object instantiateType(Class<?> type) throws Exception {
    if (type.isPrimitive()) return Defaults.defaultValue(type);
    else if (type == Void.class) return null;
    else if (type.isArray()) return Array.newInstance(type, 0);
    else if (type.isInterface())
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          new Class[] {type},
          new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
              return null;
            }
          });

    // Take a constructor with as few params as possible
    Constructor constructor = type.getDeclaredConstructors()[0];
    for (Constructor<?> c : type.getDeclaredConstructors()) {
      if (c.getParameterTypes().length < constructor.getParameterTypes().length) constructor = c;
    }

    Object[] params = new Object[constructor.getParameterTypes().length];
    for (int i = 0; i < constructor.getParameterTypes().length; i++) {
      params[i] = instantiateType(constructor.getParameterTypes()[i]);
    }
    return constructor.newInstance(params);
  }
示例#9
0
 /**
  * Gets the datatype of the object.
  *
  * @param obj the object
  * @return the type
  */
 public static String getDataType(Object obj) {
   if (obj == null) {
     return null;
   }
   if (obj instanceof String) {
     return "string"; //$NON-NLS-1$
   } else if (obj instanceof Collection) {
     return "collection"; //$NON-NLS-1$
   } else if (obj.getClass().isArray()) {
     // make sure ultimate component class is acceptable
     Class componentType = obj.getClass().getComponentType();
     while (componentType.isArray()) {
       componentType = componentType.getComponentType();
     }
     String type = componentType.getName();
     if (type.indexOf(".") == -1
         && "intdoubleboolean".indexOf(type) == -1) { // $NON-NLS-1$ //$NON-NLS-2$
       return null;
     }
     return "array"; //$NON-NLS-1$
   } else if (obj instanceof Double) {
     return "double"; //$NON-NLS-1$
   } else if (obj instanceof Integer) {
     return "int"; //$NON-NLS-1$
   } else {
     return "object"; //$NON-NLS-1$
   }
 }
 public boolean isOrdered() {
   Class cls = resolveClass();
   return List.class.isAssignableFrom(cls)
       || SortedSet.class.isAssignableFrom(cls)
       || cls.isArray()
       || LinkedHashSet.class.isAssignableFrom(cls);
 }
示例#11
0
  private static AnnotationPropertyVal rebuild(
      String key, Class annotationClass, String valueStr, TypeResolver resolver)
      throws NoSuchMethodException {
    Method prop = annotationClass.getMethod(key);
    Class returnType = prop.getReturnType();
    Object val = decode(returnType, valueStr, resolver);
    AnnotationPropertyVal.ValType valType;
    if (returnType.isPrimitive()) {
      valType = AnnotationPropertyVal.ValType.PRIMITIVE;
    } else if (returnType.isEnum()) {
      valType = AnnotationPropertyVal.ValType.ENUMERATION;
    } else if (returnType.isArray()) {

      if (returnType.getComponentType().isEnum()) {
        valType = AnnotationPropertyVal.ValType.ENUMARRAY;
      } else if (returnType.getComponentType().isPrimitive()) {
        valType = AnnotationPropertyVal.ValType.PRIMARRAY;
      } else if (String.class.equals(returnType.getComponentType())) {
        valType = AnnotationPropertyVal.ValType.STRINGARRAY;
      } else {
        valType = AnnotationPropertyVal.ValType.CLASSARRAY;
      }

    } else if (String.class.equals(returnType)) {
      valType = AnnotationPropertyVal.ValType.STRING;
    } else {
      valType = AnnotationPropertyVal.ValType.KLASS;
    }

    AnnotationPropertyVal pv = new AnnotationPropertyVal(key, returnType, val, valType);
    return pv;
  }
 /**
  * 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());
 }
示例#13
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;
  }
示例#14
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param value The value of the XML attribute containing the prop value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, String value) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)) {
      return parseBasicType(type, value);
    } else if (String.class.isAssignableFrom(type)) {
      return value;
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return parseDate(value, JOXDateHandler.determineDateFormat());
    } else {
      return null;
    }
  }
示例#15
0
文件: Query.java 项目: aaberg/sql2o
  public <T> Query addParameter(String name, Class<T> parameterClass, T value) {
    // TODO: must cover most of types: BigDecimal,Boolean,SmallInt,Double,Float,byte[]
    if (InputStream.class.isAssignableFrom(parameterClass))
      return addParameter(name, (InputStream) value);
    if (Integer.class == parameterClass) return addParameter(name, (Integer) value);
    if (Long.class == parameterClass) return addParameter(name, (Long) value);
    if (String.class == parameterClass) return addParameter(name, (String) value);
    if (Timestamp.class == parameterClass) return addParameter(name, (Timestamp) value);
    if (Time.class == parameterClass) return addParameter(name, (Time) value);

    if (parameterClass.isArray()
        // byte[] is used for blob already
        && byte[].class != parameterClass) {
      return addParameter(name, toObjectArray(value));
    }
    if (Collection.class.isAssignableFrom(parameterClass)) {
      return addParameter(name, (Collection) value);
    }

    final Object convertedValue = convertParameter(value);

    addParameterInternal(
        name,
        new ParameterSetter() {
          public void setParameter(int paramIdx, PreparedStatement statement) throws SQLException {
            getConnection()
                .getSql2o()
                .getQuirks()
                .setParameter(statement, paramIdx, convertedValue);
          }
        });

    return this;
  }
示例#16
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);
    }
  }
示例#17
0
 private static Object decode(Class returnType, String valueStr, TypeResolver resolver) {
   if (returnType.isArray()) {
     int sIndex = valueStr.indexOf("{");
     int eIndex = valueStr.lastIndexOf("}");
     String content = valueStr.substring(sIndex + 1, eIndex).trim();
     StringTokenizer tok = new StringTokenizer(content, ",");
     Object ar =
         java.lang.reflect.Array.newInstance(returnType.getComponentType(), tok.countTokens());
     int j = 0;
     while (tok.hasMoreElements()) {
       java.lang.reflect.Array.set(
           ar, j++, decode(returnType.getComponentType(), tok.nextToken(), resolver));
     }
     return ar;
   } else if (returnType.isEnum()) {
     try {
       String value = valueStr.trim();
       if (value.indexOf('.') > 0) {
         value = valueStr.substring(valueStr.lastIndexOf(".") + 1);
       }
       return returnType.getMethod("valueOf", String.class).invoke(null, value);
     } catch (IllegalAccessException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (InvocationTargetException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     } catch (NoSuchMethodException e) {
       e.printStackTrace(); // To change body of catch statement use File | Settings | File
       // Templates.
     }
   } else if (String.class.equals(returnType)) {
     return unquote(valueStr);
   } else if (boolean.class.equals(returnType)) {
     return Boolean.valueOf(valueStr);
   } else if (int.class.equals(returnType)) {
     return Integer.valueOf(valueStr);
   } else if (double.class.equals(returnType)) {
     return Double.valueOf(valueStr);
   } else if (long.class.equals(returnType)) {
     return Long.valueOf(valueStr);
   } else if (float.class.equals(returnType)) {
     return Float.valueOf(valueStr);
   } else if (short.class.equals(returnType)) {
     return Short.valueOf(valueStr);
   } else if (char.class.equals(returnType)) {
     return unquote(valueStr).charAt(0);
   } else if (Class.class.equals(returnType)) {
     try {
       String cName = valueStr.trim().replace(".class", "");
       return resolver.resolveType(cName);
     } catch (ClassNotFoundException cnfe) {
       cnfe.printStackTrace();
       return Object.class;
     }
   }
   return null;
 }
 /**
  * Estimates a "shallow" memory usage of the given object. For arrays, this will be the memory
  * taken by array storage (no subreferences will be followed). For objects, this will be the
  * memory taken by the fields.
  *
  * <p>JVM object alignments are also applied.
  */
 public static long shallowSizeOf(Object obj) {
   if (obj == null) return 0;
   final Class<?> clz = obj.getClass();
   if (clz.isArray()) {
     return shallowSizeOfArray(obj);
   } else {
     return shallowSizeOfInstance(clz);
   }
 }
 private static boolean isJSONArray(Class<?> clazz) {
   if (clazz.isArray()) {
     return true;
   }
   if (Collection.class.isAssignableFrom(clazz)) {
     return true;
   }
   return false;
 }
示例#20
0
  @SuppressWarnings("unchecked")
  public static <T> T coerceClassic(Class<T> clz, Object value) {

    if (clz == null || value == null) {
      return null;
    }

    if (clz == value.getClass()) {
      return (T) value;
    }

    if (clz == Typ.string || clz == Typ.chars) {
      return (T) value.toString();
    } else if (clz == Typ.integer || clz == Typ.intgr) {
      Integer i = toInt(value);
      return (T) i;
    } else if (clz == Typ.longWrapper || clz == Typ.lng) {
      Long l = toLong(value);
      return (T) l;
    } else if (clz == Typ.doubleWrapper || clz == Typ.dbl) {
      Double i = toDouble(value);
      return (T) i;
    } else if (clz == Typ.date) {
      return (T) toDate(value);
    } else if (clz == Typ.bigInteger) {
      return (T) toBigInteger(value);
    } else if (clz == Typ.bigDecimal) {
      return (T) toBigDecimal(value);
    } else if (clz == Typ.calendar) {
      return (T) toCalendar(toDate(value));
    } else if (clz == Typ.floatWrapper || clz == Typ.flt) {
      Float i = toFloat(value);
      return (T) i;
    } else if (clz == Typ.stringArray) {
      die("Need to fix this");
      return null;
    } else if (clz == Typ.bool || clz == Typ.bln) {
      Boolean b = toBoolean(value);
      return (T) b;
    } else if (Typ.isMap(clz)) {
      return (T) toMap(value);
    } else if (clz.isArray()) {
      return toPrimitiveArrayIfPossible(clz, value);
    } else if (Typ.isCollection(clz)) {
      return toCollection(clz, value);
    } else if (clz.getPackage() != null
        && !clz.getPackage().getName().startsWith("java")
        && Typ.isMap(value.getClass())
        && Typ.doesMapHaveKeyTypeString(value)) {
      return (T) MapObjectConversion.fromMap((Map<String, Object>) value);
    } else if (clz.isEnum()) {
      return (T) toEnum((Class<? extends Enum>) clz, value);

    } else {
      return null;
    }
  }
 @Test
 public void testSourceName() throws Exception {
   for (Class<?> type : standardTypes) {
     if (type.isArray()) {
       assertThat(describe(type).getActualName(), is(type.getComponentType().getName() + "[]"));
     } else {
       assertThat(describe(type).getActualName(), is(type.getName()));
     }
   }
 }
示例#22
0
  public static void premain(String args, Instrumentation inst) throws Exception {
    try {
      String[] agentArgs;
      if (args == null) agentArgs = new String[] {""};
      else agentArgs = args.split(",");
      if (!agentArgs[0].equals("instrumenting")) jarFileName = agentArgs[0];
      BaseClassTransformer rct = null;
      rct = new BaseClassTransformer();
      if (agentArgs[0].equals("instrumenting")) {
        initVMClasses = new HashSet<String>();
        for (Class<?> c : inst.getAllLoadedClasses()) {
          ((Set<String>) initVMClasses).add(c.getName());
        }
      }
      if (!agentArgs[0].equals("instrumenting")) {

        inst.addTransformer(rct);
        Tracer.setLocals(new CounterThreadLocal());
        Tracer.overrideAll(true);
        for (Class<?> c : inst.getAllLoadedClasses()) {
          try {
            if (c.isInterface()) continue;
            if (c.isArray()) continue;
            byte[] bytes = rct.getBytes(c.getName());
            if (bytes == null) {
              continue;
            }
            inst.redefineClasses(new ClassDefinition[] {new ClassDefinition(c, bytes)});
          } catch (Throwable e) {
            synchronized (System.err) {
              System.err.println("" + c + " failed...");
              e.printStackTrace();
            }
          }
        }
        Runtime.getRuntime()
            .addShutdownHook(
                new Thread() {
                  public void run() {
                    Tracer.mark();
                    try {
                      PrintStream ps = new PrintStream("bailout.txt");
                      ps.println("Bailouts: " + Tracer.getBailoutCount());
                      ps.close();
                    } catch (Exception e) {
                    }
                    Tracer.unmark();
                  }
                });
        if ("true".equals(System.getProperty("bci.observerOn"))) Tracer.overrideAll(false);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#23
0
 int[] arrayDimensions(Object a_object) {
   int count = 0;
   for (Class clazz = a_object.getClass(); clazz.isArray(); clazz = clazz.getComponentType()) {
     count++;
   }
   int dim[] = new int[count];
   for (int i = 0; i < count; i++) {
     dim[i] = Array.getLength(a_object);
     a_object = Array.get(a_object, 0);
   }
   return dim;
 }
 private void assertEQ(T t, Object returned) {
   if (rtype.isArray()) {
     Asserts.assertEQ(t.getClass(), returned.getClass());
     int n = Array.getLength(t);
     Asserts.assertEQ(n, Array.getLength(returned));
     for (int i = 0; i < n; ++i) {
       Asserts.assertEQ(Array.get(t, i), Array.get(returned, i));
     }
   } else {
     Asserts.assertEQ(t, returned);
   }
 }
示例#25
0
  /** Write a {@link Writable}, {@link String}, primitive type, or an array of the preceding. */
  public static void writeObject(
      DataOutput out, Object instance, Class declaredClass, Configuration conf) throws IOException {

    if (instance == null) { // null
      instance = new NullInstance(declaredClass, conf);
      declaredClass = Writable.class;
    }

    UTF8.writeString(out, declaredClass.getName()); // always write declared

    if (declaredClass.isArray()) { // array
      int length = Array.getLength(instance);
      out.writeInt(length);
      for (int i = 0; i < length; i++) {
        writeObject(out, Array.get(instance, i), declaredClass.getComponentType(), conf);
      }

    } else if (declaredClass == String.class) { // String
      UTF8.writeString(out, (String) instance);

    } else if (declaredClass.isPrimitive()) { // primitive type

      if (declaredClass == Boolean.TYPE) { // boolean
        out.writeBoolean(((Boolean) instance).booleanValue());
      } else if (declaredClass == Character.TYPE) { // char
        out.writeChar(((Character) instance).charValue());
      } else if (declaredClass == Byte.TYPE) { // byte
        out.writeByte(((Byte) instance).byteValue());
      } else if (declaredClass == Short.TYPE) { // short
        out.writeShort(((Short) instance).shortValue());
      } else if (declaredClass == Integer.TYPE) { // int
        out.writeInt(((Integer) instance).intValue());
      } else if (declaredClass == Long.TYPE) { // long
        out.writeLong(((Long) instance).longValue());
      } else if (declaredClass == Float.TYPE) { // float
        out.writeFloat(((Float) instance).floatValue());
      } else if (declaredClass == Double.TYPE) { // double
        out.writeDouble(((Double) instance).doubleValue());
      } else if (declaredClass == Void.TYPE) { // void
      } else {
        throw new IllegalArgumentException("Not a primitive: " + declaredClass);
      }
    } else if (declaredClass.isEnum()) { // enum
      UTF8.writeString(out, ((Enum) instance).name());
    } else if (Writable.class.isAssignableFrom(declaredClass)) { // Writable
      UTF8.writeString(out, instance.getClass().getName());
      ((Writable) instance).write(out);

    } else {
      throw new IOException("Can't write: " + instance + " as " + declaredClass);
    }
  }
 static String jni_signature(Class c) {
   if (c == int.class) return "I";
   if (c == long.class) return "J";
   if (c == short.class) return "S";
   if (c == byte.class) return "B";
   if (c == boolean.class) return "Z";
   if (c == double.class) return "D";
   if (c == float.class) return "F";
   if (c == char.class) return "C";
   if (c == void.class) return "V";
   if (c.isArray()) return "[" + jni_signature(c.getComponentType());
   return "L" + name(c) + ";";
 }
示例#27
0
  @Override
  @SuppressWarnings("unchecked")
  public <T> T fromString(String content, Class<T> classOfT) {
    if (!classOfT.isArray()) {
      if (Collection.class.isAssignableFrom(classOfT)) {
        // Collections are NOT supported for deserialization from CSV
        throw new RuntimeException(
            "Collection types are not supported. Please specify an array[] type.");
      }
      throw new RuntimeException(
          String.format("Array[] types are required. Please specify %s[]", classOfT.getName()));
    }

    Class<?> objectType = classOfT.getComponentType();
    int currentLine = 0;
    try (CSVParser parser = new CSVParser(new StringReader(content), getCSVFormat().withHeader())) {
      Set<String> columns = parser.getHeaderMap().keySet();
      Map<String, Field> fieldMap = getFieldMap(objectType);

      Constructor<?> objectConstructor;
      try {
        objectConstructor = objectType.getConstructor();
      } catch (NoSuchMethodException e) {
        throw new RuntimeException("A default constructor is required for " + objectType.getName());
      }

      List objects = new ArrayList<>();
      for (CSVRecord record : parser) {
        currentLine++;

        Object o = objectConstructor.newInstance();
        for (String column : columns) {
          Field field = fieldMap.get(caseSensitiveFieldNames ? column : column.toLowerCase());
          String value = record.get(column);
          Object object = objectFromString(value, field.getType());
          field.set(o, object);
        }

        objects.add(o);
      }

      Object array = Array.newInstance(objectType, objects.size());
      for (int i = 0; i < objects.size(); i++) {
        Array.set(array, i, objects.get(i));
      }

      return (T) array;
    } catch (Exception e) {
      throw new RuntimeException("Failed to parse CSV near line #" + currentLine, e);
    }
  }
示例#28
0
  public Document serialize(Object object, Document doc) {
    Class c = object.getClass();
    Integer id = getID(object);
    map.put(object, id);
    String mapSize = Integer.toString(map.size());

    // creating serialization objects
    Element objectElement = new Element("object");
    objectElement.setAttribute(new Attribute("class", c.getName()));
    objectElement.setAttribute(new Attribute("id", mapSize));
    doc.getRootElement().addContent(objectElement);

    if (!c.isArray()) // class is not an array
    {
      Field[] fields = c.getDeclaredFields();
      ArrayList<Element> fieldXML = serializeFields(fields, object, doc);
      for (int i = 0; i < fieldXML.size(); i++) {
        objectElement.addContent(fieldXML.get(i));
      }
    } else // class is an array
    {
      Object array = object;
      objectElement.setAttribute(new Attribute("length", Integer.toString(Array.getLength(array))));
      if (c.getComponentType().isPrimitive()) // class is array of primitives
      {
        for (int i = 0; i < Array.getLength(array); i++) {
          Element value = new Element("value");
          value.setText(Array.get(c, i).toString());
          objectElement.addContent(value);
        }
      } else // class is array of references
      {
        for (int j = 0; j < Array.getLength(array); j++) {
          Element ref = new Element("reference");
          id = getID(Array.get(c, j));
          if (id != -1) {
            ref.setText(Integer.toString(id));
          }
        }
        for (int k = 0; k < Array.getLength(array); k++) {
          serialize(Array.get(array, k), doc);
        }
      }
    }
    if (currentElement == 0) {
      referenceID = 0;
    }

    return doc;
  }
示例#29
0
 /**
  * Check if the given element is an array.
  *
  * <p>Multidimensional arrays are not supported.
  *
  * <p>Non-empty 1-dimensional arrays of CompositeData and TabularData are not handled as arrays
  * but as tabular data.
  */
 public static boolean isSupportedArray(Object elem) {
   if (elem == null || !elem.getClass().isArray()) {
     return false;
   }
   Class<?> ct = elem.getClass().getComponentType();
   if (ct.isArray()) {
     return false;
   }
   if (Array.getLength(elem) > 0
       && (CompositeData.class.isAssignableFrom(ct) || TabularData.class.isAssignableFrom(ct))) {
     return false;
   }
   return true;
 }
示例#30
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param element The XML element containing the property value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, Element element) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)
        || String.class.isAssignableFrom(type)) {
      return readBasicType(type, element);
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return readDate(element);
    } else {
      try {
        // If it's an object, create a new instance of the object (it should
        // be a bean, or there will be trouble)
        Object newOb = type.newInstance();

        // Copy the XML element into the bean
        readObject(newOb, element);

        return newOb;
      } catch (InstantiationException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      }
    }
  }