001/* 002 * Copyright (C) 2012 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.testing; 018 019import static com.google.common.base.Preconditions.checkArgument; 020 021import com.google.common.annotations.Beta; 022import com.google.common.annotations.GwtIncompatible; 023import com.google.common.base.CharMatcher; 024import com.google.common.base.Charsets; 025import com.google.common.base.Defaults; 026import com.google.common.base.Equivalence; 027import com.google.common.base.Joiner; 028import com.google.common.base.Predicate; 029import com.google.common.base.Predicates; 030import com.google.common.base.Splitter; 031import com.google.common.base.Stopwatch; 032import com.google.common.base.Ticker; 033import com.google.common.collect.BiMap; 034import com.google.common.collect.ClassToInstanceMap; 035import com.google.common.collect.ImmutableBiMap; 036import com.google.common.collect.ImmutableClassToInstanceMap; 037import com.google.common.collect.ImmutableCollection; 038import com.google.common.collect.ImmutableList; 039import com.google.common.collect.ImmutableListMultimap; 040import com.google.common.collect.ImmutableMap; 041import com.google.common.collect.ImmutableMultimap; 042import com.google.common.collect.ImmutableMultiset; 043import com.google.common.collect.ImmutableSet; 044import com.google.common.collect.ImmutableSetMultimap; 045import com.google.common.collect.ImmutableSortedMap; 046import com.google.common.collect.ImmutableSortedMultiset; 047import com.google.common.collect.ImmutableSortedSet; 048import com.google.common.collect.ImmutableTable; 049import com.google.common.collect.Iterators; 050import com.google.common.collect.ListMultimap; 051import com.google.common.collect.MapDifference; 052import com.google.common.collect.Maps; 053import com.google.common.collect.Multimap; 054import com.google.common.collect.Multimaps; 055import com.google.common.collect.Multiset; 056import com.google.common.collect.Ordering; 057import com.google.common.collect.PeekingIterator; 058import com.google.common.collect.Range; 059import com.google.common.collect.RowSortedTable; 060import com.google.common.collect.SetMultimap; 061import com.google.common.collect.Sets; 062import com.google.common.collect.SortedMapDifference; 063import com.google.common.collect.SortedMultiset; 064import com.google.common.collect.SortedSetMultimap; 065import com.google.common.collect.Table; 066import com.google.common.collect.Tables; 067import com.google.common.collect.TreeBasedTable; 068import com.google.common.collect.TreeMultimap; 069import com.google.common.io.ByteSink; 070import com.google.common.io.ByteSource; 071import com.google.common.io.ByteStreams; 072import com.google.common.io.CharSink; 073import com.google.common.io.CharSource; 074import com.google.common.primitives.Primitives; 075import com.google.common.primitives.UnsignedInteger; 076import com.google.common.primitives.UnsignedLong; 077import java.io.ByteArrayInputStream; 078import java.io.ByteArrayOutputStream; 079import java.io.File; 080import java.io.InputStream; 081import java.io.OutputStream; 082import java.io.PrintStream; 083import java.io.PrintWriter; 084import java.io.Reader; 085import java.io.Serializable; 086import java.io.StringReader; 087import java.io.StringWriter; 088import java.io.Writer; 089import java.lang.reflect.AnnotatedElement; 090import java.lang.reflect.Array; 091import java.lang.reflect.Constructor; 092import java.lang.reflect.Field; 093import java.lang.reflect.GenericDeclaration; 094import java.lang.reflect.InvocationTargetException; 095import java.lang.reflect.Modifier; 096import java.lang.reflect.Type; 097import java.math.BigDecimal; 098import java.math.BigInteger; 099import java.nio.Buffer; 100import java.nio.ByteBuffer; 101import java.nio.CharBuffer; 102import java.nio.DoubleBuffer; 103import java.nio.FloatBuffer; 104import java.nio.IntBuffer; 105import java.nio.LongBuffer; 106import java.nio.ShortBuffer; 107import java.nio.charset.Charset; 108import java.util.ArrayDeque; 109import java.util.Arrays; 110import java.util.Collection; 111import java.util.Comparator; 112import java.util.Currency; 113import java.util.Deque; 114import java.util.Iterator; 115import java.util.List; 116import java.util.ListIterator; 117import java.util.Locale; 118import java.util.Map; 119import java.util.NavigableMap; 120import java.util.NavigableSet; 121import java.util.Optional; 122import java.util.OptionalDouble; 123import java.util.OptionalInt; 124import java.util.OptionalLong; 125import java.util.Queue; 126import java.util.Random; 127import java.util.Set; 128import java.util.SortedMap; 129import java.util.SortedSet; 130import java.util.UUID; 131import java.util.concurrent.BlockingDeque; 132import java.util.concurrent.BlockingQueue; 133import java.util.concurrent.ConcurrentHashMap; 134import java.util.concurrent.ConcurrentMap; 135import java.util.concurrent.ConcurrentNavigableMap; 136import java.util.concurrent.ConcurrentSkipListMap; 137import java.util.concurrent.CountDownLatch; 138import java.util.concurrent.Executor; 139import java.util.concurrent.LinkedBlockingDeque; 140import java.util.concurrent.ScheduledThreadPoolExecutor; 141import java.util.concurrent.ThreadFactory; 142import java.util.concurrent.ThreadPoolExecutor; 143import java.util.concurrent.TimeUnit; 144import java.util.logging.Level; 145import java.util.logging.Logger; 146import java.util.regex.MatchResult; 147import java.util.regex.Matcher; 148import java.util.regex.Pattern; 149import java.util.stream.Stream; 150import org.checkerframework.checker.nullness.qual.Nullable; 151 152/** 153 * Supplies an arbitrary "default" instance for a wide range of types, often useful in testing 154 * utilities. 155 * 156 * <p>Covers arrays, enums and common types defined in {@code java.lang}, {@code java.lang.reflect}, 157 * {@code java.io}, {@code java.nio}, {@code java.math}, {@code java.util}, {@code 158 * java.util.concurrent}, {@code java.util.regex}, {@code com.google.common.base}, {@code 159 * com.google.common.collect} and {@code com.google.common.primitives}. In addition, if the type 160 * exposes at least one public static final constant of the same type, one of the constants will be 161 * used; or if the class exposes a public parameter-less constructor then it will be "new"d and 162 * returned. 163 * 164 * <p>All default instances returned by {@link #get} are generics-safe. Clients won't get type 165 * errors for using {@code get(Comparator.class)} as a {@code Comparator<Foo>}, for example. 166 * Immutable empty instances are returned for collection types; {@code ""} for string; {@code 0} for 167 * number types; reasonable default instance for other stateless types. For mutable types, a fresh 168 * instance is created each time {@code get()} is called. 169 * 170 * @author Kevin Bourrillion 171 * @author Ben Yu 172 * @since 12.0 173 */ 174@Beta 175@GwtIncompatible 176public final class ArbitraryInstances { 177 178 private static final Ordering<Field> BY_FIELD_NAME = 179 new Ordering<Field>() { 180 @Override 181 public int compare(Field left, Field right) { 182 return left.getName().compareTo(right.getName()); 183 } 184 }; 185 186 /** 187 * Returns a new {@code MatchResult} that corresponds to a successful match. Apache Harmony (used 188 * in Android) requires a successful match in order to generate a {@code MatchResult}: 189 * http://goo.gl/5VQFmC 190 */ 191 private static MatchResult newMatchResult() { 192 Matcher matcher = Pattern.compile(".").matcher("X"); 193 matcher.find(); 194 return matcher.toMatchResult(); 195 } 196 197 private static final ClassToInstanceMap<Object> DEFAULTS = 198 ImmutableClassToInstanceMap.builder() 199 // primitives 200 .put(Object.class, "") 201 .put(Number.class, 0) 202 .put(UnsignedInteger.class, UnsignedInteger.ZERO) 203 .put(UnsignedLong.class, UnsignedLong.ZERO) 204 .put(BigInteger.class, BigInteger.ZERO) 205 .put(BigDecimal.class, BigDecimal.ZERO) 206 .put(CharSequence.class, "") 207 .put(String.class, "") 208 .put(Pattern.class, Pattern.compile("")) 209 .put(MatchResult.class, newMatchResult()) 210 .put(TimeUnit.class, TimeUnit.SECONDS) 211 .put(Charset.class, Charsets.UTF_8) 212 .put(Currency.class, Currency.getInstance(Locale.US)) 213 .put(Locale.class, Locale.US) 214 .put(Optional.class, Optional.empty()) 215 .put(OptionalInt.class, OptionalInt.empty()) 216 .put(OptionalLong.class, OptionalLong.empty()) 217 .put(OptionalDouble.class, OptionalDouble.empty()) 218 .put(UUID.class, UUID.randomUUID()) 219 // common.base 220 .put(CharMatcher.class, CharMatcher.none()) 221 .put(Joiner.class, Joiner.on(',')) 222 .put(Splitter.class, Splitter.on(',')) 223 .put(com.google.common.base.Optional.class, com.google.common.base.Optional.absent()) 224 .put(Predicate.class, Predicates.alwaysTrue()) 225 .put(Equivalence.class, Equivalence.equals()) 226 .put(Ticker.class, Ticker.systemTicker()) 227 .put(Stopwatch.class, Stopwatch.createUnstarted()) 228 // io types 229 .put(InputStream.class, new ByteArrayInputStream(new byte[0])) 230 .put(ByteArrayInputStream.class, new ByteArrayInputStream(new byte[0])) 231 .put(Readable.class, new StringReader("")) 232 .put(Reader.class, new StringReader("")) 233 .put(StringReader.class, new StringReader("")) 234 .put(Buffer.class, ByteBuffer.allocate(0)) 235 .put(CharBuffer.class, CharBuffer.allocate(0)) 236 .put(ByteBuffer.class, ByteBuffer.allocate(0)) 237 .put(ShortBuffer.class, ShortBuffer.allocate(0)) 238 .put(IntBuffer.class, IntBuffer.allocate(0)) 239 .put(LongBuffer.class, LongBuffer.allocate(0)) 240 .put(FloatBuffer.class, FloatBuffer.allocate(0)) 241 .put(DoubleBuffer.class, DoubleBuffer.allocate(0)) 242 .put(File.class, new File("")) 243 .put(ByteSource.class, ByteSource.empty()) 244 .put(CharSource.class, CharSource.empty()) 245 .put(ByteSink.class, NullByteSink.INSTANCE) 246 .put(CharSink.class, NullByteSink.INSTANCE.asCharSink(Charsets.UTF_8)) 247 // All collections are immutable empty. So safe for any type parameter. 248 .put(Iterator.class, ImmutableSet.of().iterator()) 249 .put(PeekingIterator.class, Iterators.peekingIterator(ImmutableSet.of().iterator())) 250 .put(ListIterator.class, ImmutableList.of().listIterator()) 251 .put(Iterable.class, ImmutableSet.of()) 252 .put(Collection.class, ImmutableList.of()) 253 .put(ImmutableCollection.class, ImmutableList.of()) 254 .put(List.class, ImmutableList.of()) 255 .put(ImmutableList.class, ImmutableList.of()) 256 .put(Set.class, ImmutableSet.of()) 257 .put(ImmutableSet.class, ImmutableSet.of()) 258 .put(SortedSet.class, ImmutableSortedSet.of()) 259 .put(ImmutableSortedSet.class, ImmutableSortedSet.of()) 260 .put(NavigableSet.class, Sets.unmodifiableNavigableSet(Sets.newTreeSet())) 261 .put(Map.class, ImmutableMap.of()) 262 .put(ImmutableMap.class, ImmutableMap.of()) 263 .put(SortedMap.class, ImmutableSortedMap.of()) 264 .put(ImmutableSortedMap.class, ImmutableSortedMap.of()) 265 .put(NavigableMap.class, Maps.unmodifiableNavigableMap(Maps.newTreeMap())) 266 .put(Multimap.class, ImmutableMultimap.of()) 267 .put(ImmutableMultimap.class, ImmutableMultimap.of()) 268 .put(ListMultimap.class, ImmutableListMultimap.of()) 269 .put(ImmutableListMultimap.class, ImmutableListMultimap.of()) 270 .put(SetMultimap.class, ImmutableSetMultimap.of()) 271 .put(ImmutableSetMultimap.class, ImmutableSetMultimap.of()) 272 .put( 273 SortedSetMultimap.class, 274 Multimaps.unmodifiableSortedSetMultimap(TreeMultimap.create())) 275 .put(Multiset.class, ImmutableMultiset.of()) 276 .put(ImmutableMultiset.class, ImmutableMultiset.of()) 277 .put(SortedMultiset.class, ImmutableSortedMultiset.of()) 278 .put(ImmutableSortedMultiset.class, ImmutableSortedMultiset.of()) 279 .put(BiMap.class, ImmutableBiMap.of()) 280 .put(ImmutableBiMap.class, ImmutableBiMap.of()) 281 .put(Table.class, ImmutableTable.of()) 282 .put(ImmutableTable.class, ImmutableTable.of()) 283 .put(RowSortedTable.class, Tables.unmodifiableRowSortedTable(TreeBasedTable.create())) 284 .put(ClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build()) 285 .put(ImmutableClassToInstanceMap.class, ImmutableClassToInstanceMap.builder().build()) 286 .put(Comparable.class, ByToString.INSTANCE) 287 .put(Comparator.class, AlwaysEqual.INSTANCE) 288 .put(Ordering.class, AlwaysEqual.INSTANCE) 289 .put(Range.class, Range.all()) 290 .put(MapDifference.class, Maps.difference(ImmutableMap.of(), ImmutableMap.of())) 291 .put( 292 SortedMapDifference.class, 293 Maps.difference(ImmutableSortedMap.of(), ImmutableSortedMap.of())) 294 // reflect 295 .put(AnnotatedElement.class, Object.class) 296 .put(GenericDeclaration.class, Object.class) 297 .put(Type.class, Object.class) 298 .build(); 299 300 /** 301 * type → implementation. Inherently mutable interfaces and abstract classes are mapped to their 302 * default implementations and are "new"d upon get(). 303 */ 304 private static final ConcurrentMap<Class<?>, Class<?>> implementations = Maps.newConcurrentMap(); 305 306 private static <T> void setImplementation(Class<T> type, Class<? extends T> implementation) { 307 checkArgument(type != implementation, "Don't register %s to itself!", type); 308 checkArgument( 309 !DEFAULTS.containsKey(type), "A default value was already registered for %s", type); 310 checkArgument( 311 implementations.put(type, implementation) == null, 312 "Implementation for %s was already registered", 313 type); 314 } 315 316 static { 317 setImplementation(Appendable.class, StringBuilder.class); 318 setImplementation(BlockingQueue.class, LinkedBlockingDeque.class); 319 setImplementation(BlockingDeque.class, LinkedBlockingDeque.class); 320 setImplementation(ConcurrentMap.class, ConcurrentHashMap.class); 321 setImplementation(ConcurrentNavigableMap.class, ConcurrentSkipListMap.class); 322 setImplementation(CountDownLatch.class, Dummies.DummyCountDownLatch.class); 323 setImplementation(Deque.class, ArrayDeque.class); 324 setImplementation(OutputStream.class, ByteArrayOutputStream.class); 325 setImplementation(PrintStream.class, Dummies.InMemoryPrintStream.class); 326 setImplementation(PrintWriter.class, Dummies.InMemoryPrintWriter.class); 327 setImplementation(Queue.class, ArrayDeque.class); 328 setImplementation(Random.class, Dummies.DeterministicRandom.class); 329 setImplementation( 330 ScheduledThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class); 331 setImplementation(ThreadPoolExecutor.class, Dummies.DummyScheduledThreadPoolExecutor.class); 332 setImplementation(Writer.class, StringWriter.class); 333 setImplementation(Runnable.class, Dummies.DummyRunnable.class); 334 setImplementation(ThreadFactory.class, Dummies.DummyThreadFactory.class); 335 setImplementation(Executor.class, Dummies.DummyExecutor.class); 336 } 337 338 @SuppressWarnings("unchecked") // it's a subtype map 339 @Nullable 340 private static <T> Class<? extends T> getImplementation(Class<T> type) { 341 return (Class<? extends T>) implementations.get(type); 342 } 343 344 private static final Logger logger = Logger.getLogger(ArbitraryInstances.class.getName()); 345 346 /** 347 * Returns an arbitrary instance for {@code type}, or {@code null} if no arbitrary instance can be 348 * determined. 349 */ 350 @Nullable 351 public static <T> T get(Class<T> type) { 352 T defaultValue = DEFAULTS.getInstance(type); 353 if (defaultValue != null) { 354 return defaultValue; 355 } 356 Class<? extends T> implementation = getImplementation(type); 357 if (implementation != null) { 358 return get(implementation); 359 } 360 if (type == Stream.class) { 361 return type.cast(Stream.empty()); 362 } 363 if (type.isEnum()) { 364 T[] enumConstants = type.getEnumConstants(); 365 return (enumConstants.length == 0) ? null : enumConstants[0]; 366 } 367 if (type.isArray()) { 368 return createEmptyArray(type); 369 } 370 T jvmDefault = Defaults.defaultValue(Primitives.unwrap(type)); 371 if (jvmDefault != null) { 372 return jvmDefault; 373 } 374 if (Modifier.isAbstract(type.getModifiers()) || !Modifier.isPublic(type.getModifiers())) { 375 return arbitraryConstantInstanceOrNull(type); 376 } 377 final Constructor<T> constructor; 378 try { 379 constructor = type.getConstructor(); 380 } catch (NoSuchMethodException e) { 381 return arbitraryConstantInstanceOrNull(type); 382 } 383 constructor.setAccessible(true); // accessibility check is too slow 384 try { 385 return constructor.newInstance(); 386 } catch (InstantiationException | IllegalAccessException impossible) { 387 throw new AssertionError(impossible); 388 } catch (InvocationTargetException e) { 389 logger.log(Level.WARNING, "Exception while invoking default constructor.", e.getCause()); 390 return arbitraryConstantInstanceOrNull(type); 391 } 392 } 393 394 @Nullable 395 private static <T> T arbitraryConstantInstanceOrNull(Class<T> type) { 396 Field[] fields = type.getDeclaredFields(); 397 Arrays.sort(fields, BY_FIELD_NAME); 398 for (Field field : fields) { 399 if (Modifier.isPublic(field.getModifiers()) 400 && Modifier.isStatic(field.getModifiers()) 401 && Modifier.isFinal(field.getModifiers())) { 402 if (field.getGenericType() == field.getType() && type.isAssignableFrom(field.getType())) { 403 field.setAccessible(true); 404 try { 405 T constant = type.cast(field.get(null)); 406 if (constant != null) { 407 return constant; 408 } 409 } catch (IllegalAccessException impossible) { 410 throw new AssertionError(impossible); 411 } 412 } 413 } 414 } 415 return null; 416 } 417 418 private static <T> T createEmptyArray(Class<T> arrayType) { 419 return arrayType.cast(Array.newInstance(arrayType.getComponentType(), 0)); 420 } 421 422 // Internal implementations of some classes, with public default constructor that get() needs. 423 private static final class Dummies { 424 425 public static final class InMemoryPrintStream extends PrintStream { 426 public InMemoryPrintStream() { 427 super(new ByteArrayOutputStream()); 428 } 429 } 430 431 public static final class InMemoryPrintWriter extends PrintWriter { 432 public InMemoryPrintWriter() { 433 super(new StringWriter()); 434 } 435 } 436 437 public static final class DeterministicRandom extends Random { 438 public DeterministicRandom() { 439 super(0); 440 } 441 } 442 443 public static final class DummyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor { 444 public DummyScheduledThreadPoolExecutor() { 445 super(1); 446 } 447 } 448 449 public static final class DummyCountDownLatch extends CountDownLatch { 450 public DummyCountDownLatch() { 451 super(0); 452 } 453 } 454 455 public static final class DummyRunnable implements Runnable, Serializable { 456 @Override 457 public void run() {} 458 } 459 460 public static final class DummyThreadFactory implements ThreadFactory, Serializable { 461 @Override 462 public Thread newThread(Runnable r) { 463 return new Thread(r); 464 } 465 } 466 467 public static final class DummyExecutor implements Executor, Serializable { 468 @Override 469 public void execute(Runnable command) {} 470 } 471 } 472 473 private static final class NullByteSink extends ByteSink implements Serializable { 474 private static final NullByteSink INSTANCE = new NullByteSink(); 475 476 @Override 477 public OutputStream openStream() { 478 return ByteStreams.nullOutputStream(); 479 } 480 } 481 482 // Compare by toString() to satisfy 2 properties: 483 // 1. compareTo(null) should throw NullPointerException 484 // 2. the order is deterministic and easy to understand, for debugging purpose. 485 @SuppressWarnings("ComparableType") 486 private static final class ByToString implements Comparable<Object>, Serializable { 487 private static final ByToString INSTANCE = new ByToString(); 488 489 @Override 490 public int compareTo(Object o) { 491 return toString().compareTo(o.toString()); 492 } 493 494 @Override 495 public String toString() { 496 return "BY_TO_STRING"; 497 } 498 499 private Object readResolve() { 500 return INSTANCE; 501 } 502 } 503 504 // Always equal is a valid total ordering. And it works for any Object. 505 private static final class AlwaysEqual extends Ordering<Object> implements Serializable { 506 private static final AlwaysEqual INSTANCE = new AlwaysEqual(); 507 508 @Override 509 public int compare(Object o1, Object o2) { 510 return 0; 511 } 512 513 @Override 514 public String toString() { 515 return "ALWAYS_EQUAL"; 516 } 517 518 private Object readResolve() { 519 return INSTANCE; 520 } 521 } 522 523 private ArbitraryInstances() {} 524}