Class Context


  • public class Context
    extends Object
    The context class is intended to be a statefull class shared across a single execution. Its main purpose is to hold local data and to pass it to others contributors of the serialization/deserialization chain.

    For example if you have computed in a first serializer a value and you need it later in another one, you can put it in the context by using store(String, Object) method and later retrieve it with get(String, Class) or remove it with remove(String, Class).

    You can achieve the same thing with ThreadLocalHolder that stores the data in a thread local map but it is cleaner to use this Context class as you wont have to worry about removing values from it. Indeed java web servers reuse created threads, so if you store data in a thread local variable and don't remove it, it will still be present when another request comes in and is bound to that thread! This can also lead to memory leaks! Don't forget the try-store-finally-remove block if you stick with ThreadLocalHolder.

    This class stores also the views present in the current context, those views will be applied to the matching objects during serialization and deserialization.

    Author:
    Eugen Cepoi
    See Also:
    BeanView, BeanViewConverter, ThreadLocalHolder
    • Field Detail

      • genson

        public final Genson genson
    • Method Detail

      • hasViews

        public boolean hasViews()
      • store

        public Object store​(String key,
                            Object o)
        Puts the object o in the current context indexed by key.
        Parameters:
        key - must be not null
        o -
        Returns:
        the old object associated with that key or null.
      • get

        public <T> T get​(String key,
                         Class<T> valueType)
        Returns the value mapped to key in this context or null. If the value is not of type valueType then an exception is thrown.
        Parameters:
        key - must be not null
        valueType - the type of the value, null not allowed
        Returns:
        the mapping for key or null
        Throws:
        ClassCastException - if the value mapped to key is not of type valueType.
      • remove

        public <T> T remove​(String key,
                            Class<T> valueType)
        Removes the mapping for this key from the context. If there is no mapping for that key, null is returned. If the value mapped to key is not of type valueType an ClassCastException is thrown and the mapping is not removed.
        Parameters:
        key - must be not null
        valueType - the type of the value, null not allowed
        Returns:
        the value associated to this key
        Throws:
        ClassCastException - if the value mapped to key is not of type valueType.
        See Also:
        get(String, Class)