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 11 public StringDescription() { 12 this(new StringBuilder()); 13 } 14 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 */ 27 public static String toString(SelfDescribing selfDescribing) { 28 return new StringDescription().appendDescriptionOf(selfDescribing).toString(); 29 } 30 31 /** 32 * Alias for {@link #toString(SelfDescribing)}. 33 */ 34 public static String asString(SelfDescribing selfDescribing) { 35 return toString(selfDescribing); 36 } 37 38 @Override 39 protected void append(String str) { 40 try { 41 out.append(str); 42 } catch (IOException e) { 43 throw new RuntimeException("Could not write description", e); 44 } 45 } 46 47 @Override 48 protected void append(char c) { 49 try { 50 out.append(c); 51 } catch (IOException e) { 52 throw new RuntimeException("Could not write description", e); 53 } 54 } 55 56 /** 57 * Returns the description as a string. 58 */ 59 @Override 60 public String toString() { 61 return out.toString(); 62 } 63 } 64