Skip to content

SerializeUtils

Fulminazzo edited this page Oct 2, 2023 · 1 revision

SerializeUtils are an advanced series of function created to serialize and deserialize objects in Java. While, thanks to savable objects, BearCommands accomplishes to automate all the conversion and saving of objects, it might always be helpful to keep this utility class in mind, especially for creating YamlPairs rapidly.
Here is a list of all the available functions, detailed and explained with every parameter:

public class SerializeUtils {

    /**
     * Serializes an object.
     * If it is a primitive object (integer, long, boolean...)
     * then converts it using String.valueOf().
     * If it is an instance of UUID, then converts it using object.toString().
     * Otherwise, tries to use serializeToBase64().
     * If it fails, uses object.toString().
     * @param object: the object to be converted.
     * @return the resulting string.
     */
    public static String serializeUUIDOrBase64(Object object);

    /**
     * Serializes an object into Base64.
     * @param object: the object.
     * @return the encoded object (null if failed).
     */
    public static String serializeToBase64(Object object);

    /**
     * Converts an object into an array of bytes.
     * @param object: the object.
     * @return the array of bytes (null if failed).
     */
    public static byte[] serialize(Object object);

    /**
     * Deserializes an object.
     * First tries to use all primitives "valueOf" methods
     * (Integer.valueOf(), Long.valueOf(), Boolean.valueOf).
     * If it fails, tries to use UUID.fromString() to convert it
     * to an UUID.
     * If it fails, tries to use deserializeToBase64().
     * If it fails, returns a cast to (<O>) of the given string.
     * @param string: the string to deserialize.
     * @return the resulting object.
     */
    @SuppressWarnings("unchecked")
    public static <O> O deserializeUUIDOrBase64(String string);

    /**
     * Deserializes a Base64 string into an object.
     * @param base64: the string.
     * @return the object (null if failed).
     */
    public static <O> O deserializeFromBase64(String base64);

    /**
     * Converts an array of bytes into an object.
     * @param bytes: the array of bytes.
     * @return the object (null if failed).
     */
    @SuppressWarnings("unchecked")
    public static <O> O deserialize(byte[] bytes);
}

Clone this wiki locally