/**
  * Reads an object from a {@link IMemento}. The memento's type (root) must equal the bean's {@link
  * Root} annotation name attribute.
  */
 static <T> T fromMemento(Class<T> clazz, IMemento memento) throws IOException {
   try {
     final StringWriter sw = new StringWriter();
     final XMLMemento m = XMLMemento.createWriteRoot(memento.getType());
     m.putMemento(memento);
     m.save(sw);
     return new Persister().read(clazz, new StringReader(sw.toString()));
   } catch (Exception e) {
     throw ExceptionUtils.wrapAs(IOException.class, e);
   }
 }
 /**
  * A shortcut for:
  *
  * <pre>
  * fromMemento(clazz, memento.getChild(childName))
  * </pre>
  *
  * verifying precondition that only one child of a given name exists.
  */
 static <T> T fromMemento(Class<T> clazz, IMemento memento, String childName) throws IOException {
   final IMemento[] children = memento.getChildren(childName);
   if (children.length != 1) {
     throw new IOException(
         "Expected a single node named '"
             + childName
             + "' under memento '"
             + memento.getType()
             + "'.");
   }
   return fromMemento(clazz, children[0]);
 }
  /** Convert any {@link IMemento} to a string. */
  public static String toString(IMemento memento) {
    if (!(memento instanceof XMLMemento)) {
      XMLMemento m = XMLMemento.createWriteRoot(memento.getType());
      m.putMemento(memento);
      memento = m;
    }

    try {
      final StringWriter w = new StringWriter();
      ((XMLMemento) memento).save(w);
      return w.toString();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  /** Add a child node to a given memento, named after the object's {@link Root} annotation. */
  public static void addChild(IMemento memento, Object object) throws IOException {
    checkObject(object);

    final IMemento child = toMemento(object);
    memento.createChild(child.getType()).putMemento(child);
  }