Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   * Copyright (C) 2012 The Guava Authors
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
 import static;
import  javax.annotation.Nullable;

Supplies an arbitrary "default" instance for a wide range of types, often useful in testing utilities.

Covers arrays, enums and common types defined in java.lang, java.lang.reflect,, java.nio, java.math, java.util, java.util.concurrent, java.util.regex,, and In addition, if the type exposes at least one public static final constant of the same type, one of the constants will be used; or if the class exposes a public parameter-less constructor then it will be "new"d and returned.

All default instances returned by get are generics-safe. Clients won't get type errors for using get(Comparator.class) as a Comparator<Foo>, for example. Immutable empty instances are returned for collection types; "" for string; 0 for number types; reasonable default instance for other stateless types. For mutable types, a fresh instance is created each time get() is called.

Kevin Bourrillion
Ben Yu
public final class ArbitraryInstances {
  private static final Ordering<FieldBY_FIELD_NAME = new Ordering<Field>() {
    @Override public int compare(Field leftField right) {
      return left.getName().compareTo(right.getName());
  private static final ClassToInstanceMap<ObjectDEFAULTS = ImmutableClassToInstanceMap.builder()
      // primitives
      .put(Number.class, 0)
      .put(Pattern.class, Pattern.compile(""))
      .put(MatchResult.class, Pattern.compile("").matcher("").toMatchResult())
      .put(Currency.class, Currency.getInstance(.))
      // common.base
      .put(Joiner.class, Joiner.on(','))
      .put(Splitter.class, Splitter.on(','))
      .put(Optional.class, Optional.absent())
      .put(Predicate.class, Predicates.alwaysTrue())
      .put(Equivalence.class, Equivalence.equals())
      .put(Ticker.class, Ticker.systemTicker())
      .put(Stopwatch.class, Stopwatch.createUnstarted())
      // io types
      .put(InputStream.classnew ByteArrayInputStream(new byte[0]))
      .put(ByteArrayInputStream.classnew ByteArrayInputStream(new byte[0]))
      .put(Readable.classnew StringReader(""))
      .put(Reader.classnew StringReader(""))
      .put(StringReader.classnew StringReader(""))
      .put(Buffer.class, ByteBuffer.allocate(0))
      .put(CharBuffer.class, CharBuffer.allocate(0))
      .put(ByteBuffer.class, ByteBuffer.allocate(0))
      .put(ShortBuffer.class, ShortBuffer.allocate(0))
      .put(IntBuffer.class, IntBuffer.allocate(0))
      .put(LongBuffer.class, LongBuffer.allocate(0))
      .put(FloatBuffer.class, FloatBuffer.allocate(0))
      .put(DoubleBuffer.class, DoubleBuffer.allocate(0))
      .put(File.classnew File(""))
      // All collections are immutable empty. So safe for any type parameter.
      .put(Iterator.class, Iterators.emptyIterator())
      .put(PeekingIterator.class, Iterators.peekingIterator(Iterators.emptyIterator()))
      .put(ListIterator.class, ImmutableList.of().listIterator())
      .put(Iterable.class, ImmutableSet.of())
      .put(Collection.class, ImmutableList.of())
      .put(ImmutableCollection.class, ImmutableList.of())
      .put(List.class, ImmutableList.of())
      .put(ImmutableList.class, ImmutableList.of())
      .put(Set.class, ImmutableSet.of())
      .put(ImmutableSet.class, ImmutableSet.of())
      .put(SortedSet.class, ImmutableSortedSet.of())
      .put(ImmutableSortedSet.class, ImmutableSortedSet.of())
      .put(Map.class, ImmutableMap.of())
      .put(ImmutableMap.class, ImmutableMap.of())
      .put(SortedMap.class, ImmutableSortedMap.of())
      .put(ImmutableSortedMap.class, ImmutableSortedMap.of())
      .put(Multimap.class, ImmutableMultimap.of())
      .put(ImmutableMultimap.class, ImmutableMultimap.of())
      .put(ListMultimap.class, ImmutableListMultimap.of())
      .put(ImmutableListMultimap.class, ImmutableListMultimap.of())
      .put(SetMultimap.class, ImmutableSetMultimap.of())
      .put(ImmutableSetMultimap.class, ImmutableSetMultimap.of())
      .put(SortedSetMultimap.class, Multimaps.unmodifiableSortedSetMultimap(TreeMultimap.create()))
      .put(Multiset.class, ImmutableMultiset.of())
      .put(ImmutableMultiset.class, ImmutableMultiset.of())
      .put(SortedMultiset.class, ImmutableSortedMultiset.of())
      .put(ImmutableSortedMultiset.class, ImmutableSortedMultiset.of())
      .put(BiMap.class, ImmutableBiMap.of())
      .put(ImmutableBiMap.class, ImmutableBiMap.of())
      .put(Table.class, ImmutableTable.of())
      .put(ImmutableTable.class, ImmutableTable.of())
      .put(RowSortedTable.class, Tables.unmodifiableRowSortedTable(TreeBasedTable.create()))
      .put(ClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
      .put(ImmutableClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build())
      .put(Range.class, Range.all())
      .put(MapConstraint.class, MapConstraints.notNull())
      .put(MapDifference.class, Maps.difference(ImmutableMap.of(), ImmutableMap.of()))
          Maps.difference(ImmutableSortedMap.of(), ImmutableSortedMap.of()))
      // reflect

type -> implementation. Inherently mutable interfaces and abstract classes are mapped to their default implementations and are "new"d upon get().
  private static final ConcurrentMap<Class<?>, Class<?>> implementations = Maps.newConcurrentMap();
  private static <T> void setImplementation(Class<T> typeClass<? extends T> implementation) {
    checkArgument(type != implementation"Don't register %s to itself!"type);
        "A default value was already registered for %s"type);
    checkArgument(.put(typeimplementation) == null,
        "Implementation for %s was already registered"type);
  static {
  @SuppressWarnings("unchecked"// it's a subtype map
  private static <T> Class<? extends T> getImplementation(Class<T> type) {
    return (Class<? extends T>) .get(type);
  private static final Logger logger = Logger.getLogger(ArbitraryInstances.class.getName());

Returns an arbitrary instance for type, or null if no arbitrary instance can be determined.
  @Nullable public static <T> T get(Class<T> type) {
    T defaultValue = .getInstance(type);
    if (defaultValue != null) {
      return defaultValue;
    Class<? extends T> implementation = getImplementation(type);
    if (implementation != null) {
      return get(implementation);
    if (type.isEnum()) {
      T[] enumConstants = type.getEnumConstants();
      return (enumConstants.length == 0)
          ? null
          : enumConstants[0];
    if (type.isArray()) {
      return createEmptyArray(type);
    T jvmDefault = Defaults.defaultValue(Primitives.unwrap(type));
    if (jvmDefault != null) {
      return jvmDefault;
    if (Modifier.isAbstract(type.getModifiers()) || !Modifier.isPublic(type.getModifiers())) {
      return arbitraryConstantInstanceOrNull(type);
    final Constructor<T> constructor;
    try {
      constructor = type.getConstructor();
    } catch (NoSuchMethodException e) {
      return arbitraryConstantInstanceOrNull(type);
    constructor.setAccessible(true); // accessibility check is too slow
    try {
      return constructor.newInstance();
    } catch (InstantiationException impossible) {
      throw new AssertionError(impossible);
    } catch (IllegalAccessException impossible) {
      throw new AssertionError(impossible);
    } catch (InvocationTargetException e) {
      .log(."Exception while invoking default constructor."e.getCause());
      return arbitraryConstantInstanceOrNull(type);
  @Nullable private static <T> T arbitraryConstantInstanceOrNull(Class<T> type) {
    Field[] fields = type.getDeclaredFields();
    for (Field field : fields) {
      if (Modifier.isPublic(field.getModifiers())
          && Modifier.isStatic(field.getModifiers())
          && Modifier.isFinal(field.getModifiers())) {
        if (field.getGenericType() == field.getType()
            && type.isAssignableFrom(field.getType())) {
          try {
            T constant = type.cast(field.get(null));
            if (constant != null) {
              return constant;
          } catch (IllegalAccessException impossible) {
            throw new AssertionError(impossible);
    return null;
  private static <T> T createEmptyArray(Class<T> arrayType) {
    return arrayType.cast(Array.newInstance(arrayType.getComponentType(), 0));
  // Internal implementations of some classes, with public default constructor that get() needs.
  private static final class Dummies {
    public static final class InMemoryPrintStream extends PrintStream {
      public InMemoryPrintStream() {
        super(new ByteArrayOutputStream());
    public static final class InMemoryPrintWriter extends PrintWriter {
      public InMemoryPrintWriter() {
        super(new StringWriter());
    public static final class DeterministicRandom extends Random {
      @SuppressWarnings("unused"// invoked by reflection
      public DeterministicRandom() {
    public static final class DummyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
      public DummyScheduledThreadPoolExecutor() {
    public static final class DummyCountDownLatch extends CountDownLatch {
      public DummyCountDownLatch() {
    public static final class DummyRunnable implements RunnableSerializable {
      @Override public void run() {}
    public static final class DummyThreadFactory implements ThreadFactorySerializable {
      @Override public Thread newThread(Runnable r) {
        return new Thread(r);
    public static final class DummyExecutor implements ExecutorSerializable {
      @Override public void execute(Runnable command) {}
  // Compare by toString() to satisfy 2 properties:
  // 1. compareTo(null) should throw NullPointerException
  // 2. the order is deterministic and easy to understand, for debugging purpose.
  private static final class ByToString implements Comparable<Object>, Serializable {
    private static final ByToString INSTANCE = new ByToString();
    @Override public int compareTo(Object o) {
      return toString().compareTo(o.toString());
    @Override public String toString() {
      return "BY_TO_STRING";
    private Object readResolve() {
      return ;
  // Always equal is a valid total ordering. And it works for any Object.
  private static final class AlwaysEqual extends Ordering<Objectimplements Serializable {
    private static final AlwaysEqual INSTANCE = new AlwaysEqual();
    @Override public int compare(Object o1Object o2) {
      return 0;
    @Override public String toString() {
      return "ALWAYS_EQUAL";
    private Object readResolve() {
      return ;
  private ArbitraryInstances() {}
New to GrepCode? Check out our FAQ X