001 package org.hamcrest; 002 003 import java.io.IOException; 004 005 /** 006 * A {@link Description} that is stored as a string. 007 */ 008 public class StringDescription extends BaseDescription { 009 private final Appendable out; 010 011 public StringDescription() { 012 this(new StringBuilder()); 013 } 014 015 public StringDescription(Appendable out) { 016 this.out = out; 017 } 018 019 /** 020 * Return the description of a {@link SelfDescribing} object as a String. 021 * 022 * @param selfDescribing 023 * The object to be described. 024 * @return 025 * The description of the object. 026 */ 027 public static String toString(SelfDescribing selfDescribing) { 028 return new StringDescription().appendDescriptionOf(selfDescribing).toString(); 029 } 030 031 /** 032 * Alias for {@link #toString(SelfDescribing)}. 033 */ 034 public static String asString(SelfDescribing selfDescribing) { 035 return toString(selfDescribing); 036 } 037 038 @Override 039 protected void append(String str) { 040 try { 041 out.append(str); 042 } catch (IOException e) { 043 throw new RuntimeException("Could not write description", e); 044 } 045 } 046 047 @Override 048 protected void append(char c) { 049 try { 050 out.append(c); 051 } catch (IOException e) { 052 throw new RuntimeException("Could not write description", e); 053 } 054 } 055 056 /** 057 * Returns the description as a string. 058 */ 059 @Override 060 public String toString() { 061 return out.toString(); 062 } 063 }