是否有可能使用无论是J2ME或黑莓的API?
Is it possible to serialize an object into a string or a byte array using either the J2ME or BlackBerry APIs?
感谢。
推荐答案我处理的对象序列化情况的方法是通过实现我自己来处理一切的基础设施。你没有这个API中反映,但你必须的Class.forName(),这是聊胜于无。因此,这里是我做什么...
The way I handle the object serialization case is by implementing my own infrastructure for handling everything. You don't have reflection in this API, but you do have "Class.forName()" which is better than nothing. So here's what I do...
首先,这是我有充分的序列化对象的接口实现:
First, this is the interface that I have every serializable object implement:
public interface Serializable { void serialize(DataOutput output) throws IOException; void deserialize(DataInput input) throws IOException; }的序列化()方法写入对象的字段的的DataOutput实例,而反序列化()方法设置从DataInput中实例的对象的字段。 (这些都是面向数据的I / O流同时使用普通的顶级接口,这让我有更多的灵活性)此外,实现此接口的类需要有一个默认的无参数的构造函数。当然,如果你希望你的序列化类是反对改变健壮,你可能要相应地选择底层的数据格式。 (例如,我实现了一个序列化哈希表为基础容器来处理这些案件)
The serialize() method writes the object's fields to the DataOutput instance, while the deserialize() method sets the object's fields from the DataInput instance. (these are both plain top-level interfaces used by the data-oriented I/O streams, which allows me to have more flexibility) Also, any class implementing this interface needs to have a default no-arguments constructor. Of course if you want your serialized class to be robust against change, you may want to choose your underlying data formats accordingly. (for example, I implemented a serializable hashtable as an underlying container to handle these cases)
现在,实际上序列化类实现这个接口,我有一个看起来像这样的方法:
Now, to actually serialize a class implementing this interface, I have a method that looks something like this:
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; }更多推荐
通过J2ME或BlackBerry API的序列化
发布评论