001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.marshall.swap.spi;
018
019import org.apache.juneau.marshall.*;
020
021/**
022 * A dynamic string swap that serializes objects via {@link Object#toString()} and deserializes via
023 * {@code fromString(String)}, {@code valueOf(String)}, or a single-{@code String}-argument constructor.
024 *
025 * <p>
026 * Installed automatically when a class is annotated with
027 * {@link Marshalled @Marshalled}{@code (as=STRING)}.
028 *
029 * @param <T> The normal class type.
030 */
031public class AutoStringSwap<T> extends StringSwap<T> {
032
033   private final ClassMeta<T> classMeta;
034
035   /**
036    * Constructor.
037    *
038    * @param classMeta The class meta for the normal class. Must not be <jk>null</jk>.
039    */
040   public AutoStringSwap(ClassMeta<T> classMeta) {
041      super(classMeta.inner());
042      this.classMeta = classMeta;
043   }
044
045   @Override /* Overridden from ObjectSwap */
046   public String swap(MarshallingSession session, T o) {
047      return o.toString();
048   }
049
050   @Override /* Overridden from ObjectSwap */
051   public T unswap(MarshallingSession session, String s, ClassMeta<?> hint) throws Exception {
052      return classMeta.newInstanceFromString(null, s);
053   }
054}