private void basicReject(RichIterable<Integer> iterable) {
   Collection<Integer> actual1 = ParallelIterate.reject(iterable, Predicates.greaterThan(10000));
   Collection<Integer> actual2 =
       ParallelIterate.reject(
           iterable,
           Predicates.greaterThan(10000),
           HashBag.<Integer>newBag(),
           3,
           this.executor,
           true);
   Collection<Integer> actual3 =
       ParallelIterate.reject(iterable, Predicates.greaterThan(10000), true);
   RichIterable<Integer> expected = iterable.reject(Predicates.greaterThan(10000));
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual1.getClass().getSimpleName(),
       expected,
       actual1);
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual2.getClass().getSimpleName(),
       expected.toBag(),
       actual2);
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual3.getClass().getSimpleName(),
       expected.toBag(),
       HashBag.newBag(actual3));
 }
  private void assertContains123(Collection<Integer> coll, Class<?> expectedClass) {
    assert coll.getClass() == expectedClass; // will fail with caching objectify, this is ok

    assert coll.size() == 3;
    Iterator<Integer> it = coll.iterator();
    assert it.next() == 1;
    assert it.next() == 2;
    assert it.next() == 3;
  }
 @Test
 public void selectSortedSet() {
   RichIterable<Integer> iterable = Interval.oneTo(20000).toSortedSet();
   Collection<Integer> actual1 = ParallelIterate.select(iterable, Predicates.greaterThan(10000));
   Collection<Integer> actual2 =
       ParallelIterate.select(iterable, Predicates.greaterThan(10000), true);
   RichIterable<Integer> expected = iterable.select(Predicates.greaterThan(10000));
   Assert.assertSame(expected.getClass(), actual1.getClass());
   Assert.assertSame(expected.getClass(), actual2.getClass());
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual1.getClass().getSimpleName(),
       expected,
       actual1);
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual2.getClass().getSimpleName(),
       expected,
       actual2);
 }
  private static Collection<Object> deepClone(Collection<Object> sourceCollection) {
    Collection<Object> collection = createCollection(sourceCollection.getClass());

    for (Object entry : sourceCollection) {
      collection.add(deepClone(entry));
    }

    return collection;
  }
  /**
   * Dynamically check that the members of the collection are all instances of the given type (or
   * null), and that the collection itself is of the given collection type.
   *
   * @param <E> the collection's element type
   * @param c the collection to cast
   * @param type the class of the collection's element type.
   * @return the dynamically-type checked collection.
   * @throws java.lang.ClassCastException
   */
  @SuppressWarnings("unchecked")
  static <E, TypedC extends Collection<E>> TypedC dynamicallyCastCollection(
      Collection<?> c, Class<E> type, Class<TypedC> collectionType) {
    if (c == null) return null;
    if (!collectionType.isInstance(c)) throw new ClassCastException(c.getClass().getName());
    assert checkCollectionMembers(c, type)
        : "The collection contains members with a type other than " + type.getName();

    return collectionType.cast(c);
  }
 /**
  * 转化一批bean,并不注入指定属性
  *
  * @param beans
  * @param fieldNames
  * @return
  * @throws InstantiationException
  * @throws IllegalAccessException
  * @throws InvocationTargetException
  * @throws NoSuchMethodException
  */
 public static Collection describeCollectionExcludeFields(Collection beans, String[] fieldNames)
     throws InstantiationException, IllegalAccessException, InvocationTargetException,
         NoSuchMethodException {
   Collection rst = null;
   if (beans != null) {
     rst = beans.getClass().newInstance();
     for (Object bean : beans) rst.add(describeExcludeFields(bean, fieldNames));
   }
   return rst;
 }
Example #7
0
  @SuppressWarnings("unchecked")
  public void testCreateCollection() throws Exception {
    Collection<POJO1> collection;

    collection =
        mapper.createCollection(
            POJO1.class, (Class<? extends Collection<?>>) (Class<?>) List.class, 5);
    assertEquals(ArrayList.class, collection.getClass());

    collection =
        mapper.createCollection(
            POJO1.class, (Class<? extends Collection<?>>) (Class<?>) Set.class, 5);
    assertEquals(HashSet.class, collection.getClass());

    collection =
        mapper.createCollection(
            POJO1.class, (Class<? extends Collection<?>>) (Class<?>) Queue.class, 5);
    assertEquals(PriorityQueue.class, collection.getClass());
  }
 private void basicCollectIf(RichIterable<Integer> collection) {
   Predicate<Integer> greaterThan = Predicates.greaterThan(10000);
   Collection<String> actual1 =
       ParallelIterate.collectIf(collection, greaterThan, String::valueOf);
   Collection<String> actual2 =
       ParallelIterate.collectIf(
           collection,
           greaterThan,
           String::valueOf,
           HashBag.<String>newBag(),
           3,
           this.executor,
           true);
   Collection<String> actual3 =
       ParallelIterate.collectIf(
           collection,
           greaterThan,
           String::valueOf,
           HashBag.<String>newBag(),
           3,
           this.executor,
           true);
   Bag<String> expected = collection.collectIf(greaterThan, String::valueOf).toBag();
   Verify.assertSize(10000, actual1);
   Verify.assertNotContains(String.valueOf(9000), actual1);
   Verify.assertNotContains(String.valueOf(21000), actual1);
   Verify.assertContains(String.valueOf(15976), actual1);
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual1.getClass().getSimpleName(),
       expected,
       HashBag.newBag(actual1));
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual2.getClass().getSimpleName(),
       expected,
       actual2);
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual3.getClass().getSimpleName(),
       expected,
       actual3);
 }
 private Collection cloneCollection() {
   try {
     Collection newCol = (Collection) value.getClass().newInstance();
     PropertyIterator iter = iterator();
     while (iter.hasNext()) {
       newCol.add(iter.next().clone());
     }
     return newCol;
   } catch (Exception e) {
     log.error("Couldn't clone collection", e);
     return value;
   }
 }
 private void basicCollect(RichIterable<Integer> iterable) {
   Collection<String> actual1 = ParallelIterate.collect(iterable, String::valueOf);
   Collection<String> actual2 =
       ParallelIterate.collect(
           iterable, String::valueOf, HashBag.<String>newBag(), 3, this.executor, false);
   Collection<String> actual3 = ParallelIterate.collect(iterable, String::valueOf, true);
   RichIterable<String> expected = iterable.collect(String::valueOf);
   Verify.assertSize(20000, actual1);
   Verify.assertContains(String.valueOf(20000), actual1);
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual1.getClass().getSimpleName(),
       expected,
       actual1);
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual2.getClass().getSimpleName(),
       expected.toBag(),
       actual2);
   Assert.assertEquals(
       expected.getClass().getSimpleName() + '/' + actual3.getClass().getSimpleName(),
       expected.toBag(),
       HashBag.newBag(actual3));
 }
Example #11
0
  public void test_for_issue() throws Exception {
    String jsons = "[[1,1,1,2,3],[2,3,12,3,4],[1],[2]]";

    Collection<Collection<Integer>> collections //
        = JSON.parseObject(jsons, new TypeReference<Collection<Collection<Integer>>>() {});

    Assert.assertEquals(4, collections.size());
    Assert.assertEquals(ArrayList.class, collections.getClass());

    Collection<Integer> firstItemCollection = collections.iterator().next();
    Assert.assertEquals(5, firstItemCollection.size());
    Assert.assertEquals(ArrayList.class, firstItemCollection.getClass());
  }
Example #12
0
  protected String buildSnippetAssertCollection(String expression, Collection value) {
    Random r = new Random();
    String type = value.getClass().getCanonicalName();
    String localVar = "collection_" + Math.abs(r.nextInt());
    String newCollection = type + " " + localVar + " = new " + type + "<Object>();\n";

    for (Object v : value) {
      newCollection += "\t" + localVar + ".add(" + printPrimitiveString(v) + ");\n";
    }
    newCollection +=
        "\t" + junitAssertClassName + ".assertEquals(" + localVar + ", " + expression + ");";

    return newCollection;
  }
Example #13
0
 @SuppressWarnings("unchecked")
 public void testCollection() {
   Collection<Integer> collection = new LinkedList<Integer>();
   collection.add(1);
   collection.add(2);
   collection.add(3);
   String output = dump(collection);
   assertEquals("[1, 2, 3]\n", output);
   Collection<Integer> obj = (Collection<Integer>) load(output);
   // System.out.println(obj);
   assertEquals(3, obj.size());
   assertTrue(
       "Create ArrayList by default: " + obj.getClass().toString(), obj instanceof ArrayList);
 }
 protected <K, J extends Set<V>, V> void addToMap(Map<K, J> map, K key, Collection<V> newValues) {
   J values = map.get(key);
   if (values == null) {
     try {
       values = (J) newValues.getClass().newInstance();
     } catch (InstantiationException e) {
       e.printStackTrace();
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     }
     map.put(key, values);
   }
   values.addAll(newValues);
 }
 private void basicFlatCollect(RichIterable<Integer> iterable) {
   Collection<String> actual1 = ParallelIterate.flatCollect(iterable, INT_TO_TWO_STRINGS);
   Collection<String> actual2 =
       ParallelIterate.flatCollect(
           iterable, INT_TO_TWO_STRINGS, HashBag.<String>newBag(), 3, this.executor, false);
   Collection<String> actual3 = ParallelIterate.flatCollect(iterable, INT_TO_TWO_STRINGS, true);
   RichIterable<String> expected1 = iterable.flatCollect(INT_TO_TWO_STRINGS);
   RichIterable<String> expected2 =
       iterable.flatCollect(INT_TO_TWO_STRINGS, HashBag.<String>newBag());
   Verify.assertContains(String.valueOf(20000), actual1);
   Assert.assertEquals(
       expected1.getClass().getSimpleName() + '/' + actual1.getClass().getSimpleName(),
       expected1,
       actual1);
   Assert.assertEquals(
       expected2.getClass().getSimpleName() + '/' + actual2.getClass().getSimpleName(),
       expected2,
       actual2);
   Assert.assertEquals(
       expected1.getClass().getSimpleName() + '/' + actual3.getClass().getSimpleName(),
       expected1.toBag(),
       HashBag.newBag(actual3));
 }
Example #16
0
    // creates set from specified collection with specified permission
    // all collection elements are verified before adding
    protected SecureSet(AuthPermission perm, Collection<? extends SST> s) {
      this(perm);

      // Subject's constructor receives a Set, we can trusts if a set is
      // from bootclasspath,
      // and not to check whether it contains duplicates or not
      boolean trust = s.getClass().getClassLoader() == null;

      for (SST o : s) {
        verifyElement(o);
        if (trust || !elements.contains(o)) {
          elements.add(o);
        }
      }
    }
Example #17
0
  @SuppressWarnings("unchecked")
  private void bindCollectionAssociation(MutablePropertyValues mpvs, PropertyValue pv) {
    Object v = pv.getValue();

    Collection collection = (Collection) bean.getPropertyValue(pv.getName());
    collection.clear();
    final Class associatedType = getReferencedTypeForCollection(pv.getName(), getTarget());
    final boolean isArray = v != null && v.getClass().isArray();
    final PropertyEditor propertyEditor = findCustomEditor(collection.getClass(), pv.getName());
    if (propertyEditor == null) {
      if (isDomainAssociation(associatedType)) {
        if (isArray) {
          Object[] identifiers = (Object[]) v;
          for (Object id : identifiers) {
            if (id != null) {
              associateObjectForId(pv, id, associatedType);
            }
          }
          mpvs.removePropertyValue(pv);
        } else if (v != null && (v instanceof String)) {
          associateObjectForId(pv, v, associatedType);
          mpvs.removePropertyValue(pv);
        }
      } else if (GrailsDomainConfigurationUtil.isBasicType(associatedType)) {
        if (isArray) {
          Object[] values = (Object[]) v;
          List list = collection instanceof List ? (List) collection : null;
          for (int i = 0; i < values.length; i++) {
            Object value = values[i];
            try {
              Object newValue = getTypeConverter().convertIfNecessary(value, associatedType);
              if (list != null) {
                if (i > list.size() - 1) {
                  list.add(i, newValue);
                } else {
                  list.set(i, newValue);
                }
              } else {
                collection.add(newValue);
              }
            } catch (TypeMismatchException e) {
              // ignore
            }
          }
        }
      }
    }
  }
 @Test
 public void testFilter() {
   List<String> list = newTestList();
   Collection<String> filtered =
       filter(
           list,
           new Predicate<String>() {
             @Override
             public Boolean apply(String s) {
               return "one".equals(s);
             }
           });
   assertSame(filtered.getClass(), list.getClass());
   assertEquals(2, list.size());
   assertEquals(1, filtered.size());
   assertTrue(filtered.contains("one"));
 }
  public static void testaAdicionarNaColecao(Collection colecao, int quantidade) {
    long inicio = System.currentTimeMillis();
    for (int i = 0; i < quantidade; i++) {
      colecao.add("Objeto " + i);
    }

    long termino = System.currentTimeMillis();

    System.out.println(
        "Tempo para adicionar "
            + quantidade
            + " objetos na "
            + colecao.getClass().getSimpleName()
            + " foram : "
            + (termino - inicio)
            + " Milisegundos");
  }
  // once-per-game initialization
  private void initOnce() {
    initialized = true;

    log.info("initOnce()");
    visualizerService.newRun();

    // registrations for message listeners:
    Collection<MessageHandler> handlers = context.getBeansOfType(MessageHandler.class).values();
    for (MessageHandler handler : handlers) {
      log.debug("initializing..." + handler.getClass().getName());
      handler.initialize();
    }

    Collection<DomainRepo> repos = context.getBeansOfType(DomainRepo.class).values();
    for (DomainRepo repo : repos) {
      log.debug("recycling..." + repos.getClass().getName());
      repo.recycle();
    }
  }
 @Test
 public void testFlatMap() {
   List<String> list = newTestList();
   Collection<String> mapped =
       flatMap(
           list,
           new Function<String, Collection<String>>() {
             @Override
             public Collection<String> apply(String s) {
               return list(">", s);
             }
           });
   assertSame(mapped.getClass(), list.getClass());
   assertEquals(2, list.size());
   assertEquals(4, mapped.size());
   assertTrue(mapped.contains(">"));
   assertTrue(mapped.contains("one"));
   assertTrue(mapped.contains("two"));
 }
 @Test
 public void get() throws InterruptedException {
   HazelcastClient hClient = getHazelcastClient();
   MultiMap<String, Integer> multiMap = hClient.getMultiMap("get");
   assertTrue(multiMap.put("a", 1));
   assertTrue(multiMap.put("a", 2));
   Map<Integer, CountDownLatch> map = new HashMap<Integer, CountDownLatch>();
   map.put(1, new CountDownLatch(1));
   map.put(2, new CountDownLatch(1));
   Collection<Integer> collection = multiMap.get("a");
   assertEquals(Values.class, collection.getClass());
   assertEquals(2, collection.size());
   for (Iterator<Integer> it = collection.iterator(); it.hasNext(); ) {
     Integer o = it.next();
     map.get(o).countDown();
   }
   assertTrue(map.get(1).await(10, TimeUnit.SECONDS));
   assertTrue(map.get(2).await(10, TimeUnit.SECONDS));
 }
 @Test
 public void testMap() {
   List<String> list = newTestList();
   Collection<String> mapped =
       map(
           list,
           new Function<String, String>() {
             @Override
             public String apply(String s) {
               return s + s;
             }
           });
   assertSame(mapped.getClass(), list.getClass());
   assertTrue(list.contains("one"));
   assertTrue(list.contains("two"));
   assertTrue(mapped.contains("oneone"));
   assertTrue(mapped.contains("twotwo"));
   assertEquals(2, list.size());
   assertEquals(2, mapped.size());
 }
Example #24
0
 // fail with helpful message if e.g. we are asserting a Set .equals a List
 private static void compatibleCollections(Collection a, Collection b) {
   if (a.getClass().isAssignableFrom(b.getClass())
       || b.getClass().isAssignableFrom(a.getClass())) {
     TestCase.assertEquals(a, b);
   } else {
     TestCase.fail(
         "Collections are of incompatible types: "
             + a.getClass()
             + " ("
             + a.toString()
             + ") and "
             + b.getClass()
             + " ("
             + b.toString()
             + ").");
   }
 }
Example #25
0
  /**
   * Implementation of the OCL
   *
   * <ul>
   *   <li><tt>Set::excluding(object : T) : Set(T)</tt>
   *   <li><tt>Bag::excluding(object : T) : Bag(T)</tt>
   *   <li><tt>Sequence::excluding(object : T) : Sequence(T)</tt>
   * </ul>
   *
   * operations.
   *
   * @param self the source collection
   * @param object an object
   * @return the source collection without any occurences of the object
   */
  public static <E> Collection<E> excluding(Collection<E> self, Object object) {
    Collection<E> result = null;
    if (self instanceof LinkedHashSet<?>) {
      result = createNewOrderedSet(self);
    } else if (self instanceof Set<?>) {
      result = createNewSet(self);
    } else if (self instanceof Bag<?>) {
      result = createNewBag(self);
    } else if (self instanceof List<?>) {
      List<E> resultSeq = createNewSequence(self);
      while (resultSeq.remove(
          object)) {; // for sequences we need to remove all the matching elements
      }
      return resultSeq;
    } else {
      throw new RuntimeException(
          "Unsupported collection type " + self.getClass().getName()); // $NON-NLS-1$
    }

    // non-sequences (bags remove all occurrences internally)
    result.remove(object);
    return result;
  }
Example #26
0
 DeltaAnalysisRunnable(
     LibrarySource librarySource,
     URI unitUri,
     Map<URI, String> suppliedSources,
     DartUnit suppliedUnit,
     DartNode completionNode,
     int completionLocation,
     Collection<DartCompilationError> parseErrors) {
   super(parseErrors);
   librarySource.getClass(); // quick null check
   unitUri.getClass(); // quick null check
   suppliedSources.getClass(); // quick null check
   suppliedUnit.getClass(); // quick null check
   completionNode.getClass(); // quick null check
   parseErrors.getClass(); // quick null check
   this.librarySource = new LibraryWithSuppliedSources(librarySource, suppliedSources);
   this.parsedUnit = suppliedUnit;
   this.completionNode = completionNode;
   this.completionLocation = completionLocation;
   String sourceString = suppliedSources.get(unitUri);
   this.source = new DartSourceString(unitUri.getPath(), sourceString);
   this.unitUri = unitUri;
 }
  @SuppressWarnings("unchecked")
  protected Collection convertToTypedCollection(
      Collection original, String propertyName, Class requiredType, TypeDescriptor typeDescriptor) {

    boolean originalAllowed = requiredType.isInstance(original);
    if (!originalAllowed && !Collection.class.isAssignableFrom(requiredType)) {
      return original;
    }

    MethodParameter methodParam = typeDescriptor.getMethodParameter();
    Class elementType = null;
    if (methodParam != null) {
      elementType = GenericCollectionTypeResolver.getCollectionParameterType(methodParam);
    }
    if (elementType == null
        && originalAllowed
        && !this.propertyEditorRegistry.hasCustomEditorForElement(null, propertyName)) {
      return original;
    }

    Iterator it;
    try {
      it = original.iterator();
      if (it == null) {
        if (logger.isDebugEnabled()) {
          logger.debug(
              "Collection of type ["
                  + original.getClass().getName()
                  + "] returned null Iterator - injecting original Collection as-is");
        }
        return original;
      }
    } catch (Throwable ex) {
      if (logger.isDebugEnabled()) {
        logger.debug(
            "Cannot access Collection of type ["
                + original.getClass().getName()
                + "] - injecting original Collection as-is",
            ex);
      }
      return original;
    }

    Collection convertedCopy;
    try {
      if (CollectionFactory.isApproximableCollectionType(requiredType)) {
        convertedCopy = CollectionFactory.createApproximateCollection(original, original.size());
      } else {
        convertedCopy = (Collection) requiredType.newInstance();
      }
    } catch (Throwable ex) {
      if (logger.isDebugEnabled()) {
        logger.debug(
            "Cannot create copy of Collection type ["
                + original.getClass().getName()
                + "] - injecting original Collection as-is",
            ex);
      }
      return original;
    }

    int i = 0;
    for (; it.hasNext(); i++) {
      Object element = it.next();
      String indexedPropertyName = buildIndexedPropertyName(propertyName, i);
      if (methodParam != null) {
        methodParam.increaseNestingLevel();
      }
      Object convertedElement =
          convertIfNecessary(indexedPropertyName, null, element, elementType, typeDescriptor);
      if (methodParam != null) {
        methodParam.decreaseNestingLevel();
      }
      try {
        convertedCopy.add(convertedElement);
      } catch (Throwable ex) {
        if (logger.isDebugEnabled()) {
          logger.debug(
              "Collection type ["
                  + original.getClass().getName()
                  + "] seems to be read-only - injecting original Collection as-is",
              ex);
        }
        return original;
      }
      originalAllowed = originalAllowed && (element == convertedElement);
    }
    return (originalAllowed ? original : convertedCopy);
  }
Example #28
0
  public static void main(String[] args) throws Exception {
    // 第1点:Java的泛型仅仅只是通用Java的编译器实现的,进行全安检查,编译成class文件后没有保留泛型信息
    Collection<Integer> c1 = new ArrayList<Integer>();
    Collection<String> c2 = new ArrayList<String>();
    // 1.1 获取c1与c2的字节码看是否相同
    System.out.println("c1与c2的字节码是否相同:" + (c1.getClass() == c2.getClass())); // true
    c1.add(23);
    // 1.2 通用反射我们可以向c1中添加String类型的数据(class文件没有任何泛型)
    Class clazz = c1.getClass();
    Method collAddMethod = clazz.getMethod("add", Object.class);
    collAddMethod.invoke(c1, "http://zmx.iteye.com");
    for (Object obj : c1) {
      System.out.println(obj);
    }

    // 泛型中的?通配符:表示任何类型,它与Object是有区别的如下所示:
    // collection1可以存放任保类型,而collection2则只能放在Object类型
    Collection<?> collection1 = new ArrayList<String>();
    collection1 = new ArrayList<Integer>();
    collection1 = new ArrayList<Object>();
    Collection<Object> collection2 = new ArrayList<Object>();
    // 泛型中的向上或向下限定
    // collection3表示它可以存放Number或Number的子类
    Collection<? extends Number> collection3 = null;
    collection3 = new ArrayList<Number>();
    collection3 = new ArrayList<Double>();
    collection3 = new ArrayList<Long>();
    // collection4表示它可以存放Integer或Integer的父类
    Collection<? super Integer> collection4 = null;
    collection4 = new ArrayList<Object>();

    // 泛型简单使用(Map.Entry是Map的一个内部类,表法Map中存在的一个对象)
    Map<String, Integer> testMap = new HashMap<String, Integer>();
    testMap.put("xiaobojava", 2);
    testMap.put("mengya", 3);
    testMap.put("zmx", 6);
    Set<Map.Entry<String, Integer>> entrySet = testMap.entrySet();
    for (Map.Entry<String, Integer> entry : entrySet) {
      System.out.println(entry.getKey() + ":" + entry.getValue());
    }

    // 自定义泛型
    String[] a = {"aa", "bb", "cc"};
    swap(a, 1, 2);
    Integer[] b = {32, 45, 67};
    swap(b, 1, 2);
    // 泛型中的类型不能为基本数据类型(如下就不行)
    int[] c = {1, 3, 5};
    // swap(c,1,2);

    Vector<Date> v1 = new Vector<Date>();
    // 由于泛型是由编译器实现的语法检查,编译成class文件后没有保留泛型信息,但可以根据Method获取
    Method applyMethod = GenericStudy.class.getMethod("applyVector", Vector.class);
    // getGenericParameterTypes()按照声明顺序返回 Type 对象的数组,这些对象描述了此 Method
    // 对象所表示的方法的形参类型的。
    Type[] type = applyMethod.getGenericParameterTypes();
    // ParameterizedType extends Type
    ParameterizedType pType = (ParameterizedType) type[0]; // applyVector只用一个参数
    // getRawType()返回 Type 对象,表示声明此类型的类或接口
    System.out.println("getRawType()方法:表示声明此类型的类或接口是:" + pType.getRawType());
    // getActualTypeArguments()返回表示此类型实际类型参数的 Type 对象的数组。
    System.out.println(
        "getActualTypeArguments()方法:实际类型参数的 Type 对象"
            + pType.getActualTypeArguments()[0]); // Vector<Date>只用一个Date类型
  }
  /**
   * Convert an Object to a Collection with elements of the desired type. If it is a Collection and
   * it is of the same collection and element type it is returned as is, otherwise a new Collection
   * is created with all elements converted to the desired type. If it is a String representation of
   * a Collection it is converted to a Collection.
   *
   * @param <E> The element type.
   * @param <C> The Collection type.
   * @param obj The Object to be converted.
   * @param collectionType The desired Collection type.
   * @param elementType The desired element type.
   * @param emptyIfNull Whether or not an empty Collection should be returned if the Collection
   *     could not be converted.
   * @return The converted Collection.
   */
  public <E, C extends Collection<E>> C convertToCollection(
      Object obj, Class<C> collectionType, Class<E> elementType, boolean emptyIfNull) {
    // Grab defaults for types if interfaces or non-datareference collections are provided
    Class<? extends C> constructionCollectionType;
    Class<? extends E> constructionElementType;
    if (collectionType.equals(List.class)) {
      if (DataReferencable.class.isAssignableFrom(elementType)) {
        constructionCollectionType = (Class) DataReferenceList.class;
        constructionElementType = (Class) DataReference.class;
      } else {
        constructionCollectionType = (Class) ArrayList.class;
      }
    } else if (collectionType.equals(Set.class)) {
      if (DataReferencable.class.isAssignableFrom(elementType)) {
        constructionElementType = (Class) DataReference.class;
        throw new IllegalArgumentException(
            "Set class is not supported for DataReferencable elements");
      }
      constructionCollectionType = (Class) HashSet.class;
    } else {
      constructionCollectionType = collectionType;
    }

    if (obj != null) {
      if (obj instanceof Collection) {
        // If it's already a collection
        Collection collection = (Collection) obj;
        Class cachedElementType = getCachedElementType(collection);
        // If we have cached it's element type return if same
        if (cachedElementType != null
            && elementType.isAssignableFrom(cachedElementType)
            && collection.getClass().equals(constructionCollectionType)) {
          setCachedElementType(collection, elementType);
          return (C) collection;
        } else {
          return _convertContents(collection, constructionCollectionType, elementType);
        }
      } else {
        try {
          // If it's a single value convertable to E
          E e = convert(obj, elementType);
          C c = CollectionUtils.instanceOf(constructionCollectionType);
          c.add(e);
          return c;
        } catch (ConversionException ex) {
        }
        try {
          // If it's a string representation of one or many E's
          String string = convert(obj, String.class);
          String[] split = TextUtils.splitOnSpacesAndCommas(string);
          C c = CollectionUtils.instanceOf(constructionCollectionType);
          for (String str : split) {
            try {
              E e = convert(obj, elementType);
              c.add(e);
            } catch (ConversionException ex) {

            }
          }
          if (!c.isEmpty()) {
            return c;
          }
        } catch (ConversionException ex) {

        }
      }
    }

    // Fall through to here if a collection could not be converted for any reason
    if (emptyIfNull) {
      return CollectionUtils.instanceOf(constructionCollectionType);
    } else {
      return null;
    }
  }
Example #30
0
  static void f1(Holder<List<?>> holder) {
    System.out.println("Calling methods for the Holder: ");
    System.out.println("holder: " + holder);
    System.out.println("holder.get(): " + holder.get());
    System.out.println("Calling holder.set(Arrays.asList(1,2,3)");
    holder.set(Arrays.asList(1, 2, 3));
    System.out.println("holder.get(): " + holder.get());
    int[] ia = {1, 2, 3};
    System.out.println("int[] ia = {1,2,3}");
    System.out.println("holder.equals(ia): " + holder.equals(ia));
    List iaList = Arrays.asList(ia);
    System.out.println("List iaList = Arrays.asList(ia)");
    System.out.println("holder.equals(iaList): " + holder.equals(iaList));
    List<Integer> l = new ArrayList<Integer>();
    for (int i = 1; i < 4; i++) l.add(i);
    System.out.println("l = List<Integer>() and add 1,2,3");
    System.out.println("holder.equals(l): " + holder.equals(l));
    System.out.println();

    System.out.println("Calling methods for the List: ");
    System.out.println("holder.get(): " + holder.get());
    System.out.println("holder.get().getClass(): " + holder.get().getClass());
    // Incompatible types:
    // List<? extends Integer> list = holder.get();
    // OK, but can't add anything:
    List<?> list = holder.get();
    System.out.println("list: " + list);
    // list.add(new Object());
    List list1 = holder.get(); // OK, but:
    // list1.add(new Object()); // Warning: unchecked call to add(E) and
    // UnsupportedOperationException at runtime
    System.out.println("list1.getClass(): " + list1.getClass());
    System.out.println("list.equals(list1): " + list.equals(list1));
    // list.clear(); // runtime UnsupportedOperationException
    System.out.println("list.contains(1): " + list.contains(1));
    Collection<Integer> c = new HashSet<Integer>();
    for (int i = 1; i < 4; i++) c.add(i);
    System.out.println("list.containsAll(c): " + list.containsAll(c));
    System.out.println("list.equals(c): " + list.equals(c));
    System.out.println("list = " + list);
    System.out.println("c = " + c);
    System.out.println("c.getClass(): " + c.getClass()); // c is not a List
    System.out.println("list.get(0) = " + list.get(0));
    System.out.println("list.hashCode() = " + list.hashCode());
    System.out.println("list.indexOf(2) = " + list.indexOf(2));
    ListIterator li = list.listIterator();
    System.out.println("After ListIterator li = list.listIterator():");
    System.out.println("li.next() = " + li.next());
    // runtime errors: UnsupportedOperationException:
    // list.remove(0);
    // list.removeAll(c);
    // list.retainAll(c1);
    // list.set(1,4); // compile error: set(int, ?) in list<?> cannot
    // be applied to (int,int)
    System.out.println("list.size() = " + list.size());
    System.out.println("list.subList(1,2) = " + list.subList(1, 2));
    Object[] oa = list.toArray();
    System.out.println("After Object[] oa = list.toArray():");
    System.out.println("oa = ");
    for (Object o : oa) System.out.print(o + " ");
    System.out.println();
    // Error: runtime error ArrayStoreException:
    // Double[] da = list.toArray(new Double[3]);
    Number[] na = list.toArray(new Number[3]);
    System.out.println("After Number[] na = list.toArray(new Number[3]):");
    System.out.println("na = ");
    for (Number n : na) System.out.print(n + " ");
    System.out.println();
  }