1 package org.hamcrest; 2 3 import java.io.IOException; 4 5 /** 6 * A {@link Description} that is stored as a string. 7 */ 8 public class StringDescription extends BaseDescription { 9 private final Appendable out; 10 StringDescription()11 public StringDescription() { 12 this(new StringBuilder()); 13 } 14 StringDescription(Appendable out)15 public StringDescription(Appendable out) { 16 this.out = out; 17 } 18 19 /** 20 * Return the description of a {@link SelfDescribing} object as a String. 21 * 22 * @param selfDescribing 23 * The object to be described. 24 * @return 25 * The description of the object. 26 */ toString(SelfDescribing value)27 public static String toString(SelfDescribing value) { 28 return new StringDescription().appendDescriptionOf(value).toString(); 29 } 30 31 /** 32 * Alias for {@link #toString(SelfDescribing)}. 33 */ asString(SelfDescribing selfDescribing)34 public static String asString(SelfDescribing selfDescribing) { 35 return toString(selfDescribing); 36 } 37 append(String str)38 protected void append(String str) { 39 try { 40 out.append(str); 41 } catch (IOException e) { 42 throw new RuntimeException("Could not write description", e); 43 } 44 } 45 append(char c)46 protected void append(char c) { 47 try { 48 out.append(c); 49 } catch (IOException e) { 50 throw new RuntimeException("Could not write description", e); 51 } 52 } 53 54 /** 55 * Returns the description as a string. 56 */ toString()57 public String toString() { 58 return out.toString(); 59 } 60 } 61