Serialization via the J2ME or BlackBerry API

Is it possible to serialize an object into a string or byte array using the J2ME or BlackBerry API?

Thank.

+3
source share
4 answers

The way I handle the case of serializing an object is to implement my own infrastructure to handle everything. You have no reflection in this API, but you have a Class.forName () class, which is better than nothing. So here is what I do ...

Firstly, this is the interface that I implement for each serializable object:

public interface Serializable {
    void serialize(DataOutput output) throws IOException;
    void deserialize(DataInput input) throws IOException;
}

serialize() DataOutput, deserialize() DataInput. ( , -, , ). , , , no-arguments . , , , . (, - )

, , , , :

public static byte[] serializeClass(Serializable input) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    DataOutputStream output = new DataOutputStream(buffer);
    try {
        output.writeUTF(input.getClass().getName());
        input.serialize(output);
    } catch (IOException ex) {
        // do nothing
    }
    return buffer.toByteArray();
}

:

public static Serializable deserializeClass(byte[] data) {
    DataInputStream input = new DataInputStream(new ByteArrayInputStream(data));
    Object deserializedObject;
    Serializable result = null;
    try {
        String classType = input.readUTF();
        deserializedObject = Class.forName(classType).newInstance();
        if(deserializedObject instanceof Serializable) {
            result = (Serializable)deserializedObject;
            result.deserialize(input);
        }
    } catch (IOException ex) {
        result = null;
    } catch (ClassNotFoundException ex) {
        result = null;
    } catch (InstantiationException ex) {
        result = null;
    } catch (IllegalAccessException ex) {
        result = null;
    }
    return result;
}
+6

Java ME, , API , - .

+2

- -, PersistentStore. , Boolean, Byte, Character, Integer, Long, Object, Short, String, Vector, Hashtable, .

+2

. , somesort of reflection .

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    DataOutputStream outputStream = new DataOutputStream(baos);
    try {
        // serialize your object - 
        outputStream.writeInt(this.name);
        // Then push the player name.
        outputStream.writeUTF(this.timestamp);
    }
    catch (IOException ioe) {
        System.out.println(ioe);
        ioe.printStackTrace();
    }


// Extract the byte array
byte[] b = baos.toByteArray();
+1

Source: https://habr.com/ru/post/1737027/


All Articles