guava
80 строк · 2.4 Кб
1/*
2* Copyright (C) 2008 The Guava Authors
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16
17package com.google.common.collect.testing;
18
19import com.google.common.annotations.GwtIncompatible;
20import java.io.ByteArrayInputStream;
21import java.io.ByteArrayOutputStream;
22import java.io.IOException;
23import java.io.ObjectInputStream;
24import java.io.ObjectOutputStream;
25import java.util.Collection;
26import java.util.List;
27
28/**
29* Reserializes the sets created by another test set generator.
30*
31* <p>TODO: make CollectionTestSuiteBuilder test reserialized collections
32*
33* @author Jesse Wilson
34*/
35@GwtIncompatible
36public class ReserializingTestCollectionGenerator<E> implements TestCollectionGenerator<E> {
37private final TestCollectionGenerator<E> delegate;
38
39ReserializingTestCollectionGenerator(TestCollectionGenerator<E> delegate) {
40this.delegate = delegate;
41}
42
43public static <E> ReserializingTestCollectionGenerator<E> newInstance(
44TestCollectionGenerator<E> delegate) {
45return new ReserializingTestCollectionGenerator<>(delegate);
46}
47
48@Override
49public Collection<E> create(Object... elements) {
50return reserialize(delegate.create(elements));
51}
52
53@SuppressWarnings("unchecked")
54static <T> T reserialize(T object) {
55try {
56ByteArrayOutputStream bytes = new ByteArrayOutputStream();
57ObjectOutputStream out = new ObjectOutputStream(bytes);
58out.writeObject(object);
59ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()));
60return (T) in.readObject();
61} catch (IOException | ClassNotFoundException e) {
62throw new AssertionError(e);
63}
64}
65
66@Override
67public SampleElements<E> samples() {
68return delegate.samples();
69}
70
71@Override
72public E[] createArray(int length) {
73return delegate.createArray(length);
74}
75
76@Override
77public Iterable<E> order(List<E> insertionOrder) {
78return delegate.order(insertionOrder);
79}
80}
81