All Downloads are FREE. Search and download functionalities are using the official Maven repository.

enkan.system.repl.jshell.JShellObjectTransferer Maven / Gradle / Ivy

There is a newer version: 0.10.0
Show newest version
package enkan.system.repl.jshell;

import java.io.*;
import java.util.Base64;

public class JShellObjectTransferer {
    private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder();
    private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();

    @SuppressWarnings("unchecked")
    public static  T readFromBase64(String base64, Class clazz) throws IOException, ClassNotFoundException {
        byte[] blob = BASE64_DECODER.decode(base64);
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(blob))) {
            Object obj = ois.readObject();
            if (!clazz.isInstance(obj)) {
                throw new IllegalArgumentException("Object is not a instance of " + clazz);
            }
            return (T) obj;
        }
    }

    public static String writeToBase64(Object obj) throws IOException {
        try(ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(obj);
            return BASE64_ENCODER.encodeToString(baos.toByteArray());
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy