Blame |
Last modification |
View Log
| RSS feed
package com.owlike.genson;
import java.lang.reflect.Type;
/**
* Factory interface must be implemented by classes who want to act as factories and create
* instances of Converter/Serializer/Deserializer. Implementations will be used as Converter,
* Serializer and Deserializer factories. So the type T will be something like
* Converter<Integer> but the type argument of method create will correspond to Integer <u>or
* a subclass of Integer</u>.
* <p/>
* As an example you can have a look at factories from {@link com.owlike.genson.convert.DefaultConverters
* DefaultConverters}. Here is an example with a custom converter and factory for enums.
* <p/>
* <pre>
* public static class EnumConverter<T extends Enum<T>> implements Converter<T> {
* private final Class<T> eClass;
*
* public EnumConverter(Class<T> eClass) {
* this.eClass = eClass;
* }
*
* @Override
* public void serialize(T obj, ObjectWriter writer, Context ctx) {
* writer.writeUnsafeValue(obj.name());
* }
*
* @Override
* public T deserialize(ObjectReader reader, Context ctx) {
* return Enum.valueOf(eClass, reader.valueAsString());
* }
* }
*
* public final static class EnumConverterFactory implements Factory<Converter<? extends Enum<?>>> {
* public final static EnumConverterFactory instance = new EnumConverterFactory();
*
* private EnumConverterFactory() {
* }
*
* @SuppressWarnings({ "rawtypes", "unchecked" })
* @Override
* public Converter<Enum<?>> create(Type type, Genson genson) {
* Class<?> rawClass = TypeUtil.getRawClass(type);
* return rawClass.isEnum() || Enum.class.isAssignableFrom(rawClass) ? new EnumConverter(
* rawClass) : null;
* }
* };
* </pre>
* <p/>
* Note the use of {@link com.owlike.genson.reflect.TypeUtil TypeUtil} class that provides operations to
* work with generic types. However this class might change in the future, in order to provide a better API.
*
* @param <T> the base type of the objects this factory can create. T can be of type Converter,
* Serializer or Deserializer.
* @author eugen
* @see com.owlike.genson.Converter
* @see com.owlike.genson.convert.ChainedFactory ChainedFactory
* @see com.owlike.genson.Serializer
* @see com.owlike.genson.Deserializer
*/
public interface Factory
<T
> {
/**
* Implementations of this method must try to create an instance of type T based on the
* parameter "type". If this factory can not create an object of type T for parameter type then
* it must return null.
*
* @param type used to build an instance of T.
* @return null if it doesn't support this type or an instance of T (or a subclass).
*/
public T create
(1.5.0/docs/api/java/lang/reflect/Type.html">Type type, Genson genson
);
}