将对象转换为字节数组(通过套接字发送)。然后将其转换回来
我有以下类定义:
public class Message {
private String sender, text;
public Message(String sender, String text) {
this.sender = sender;
this.text = text;
}
}
我希望能够通过蓝牙套接字发送此 Message 类的实例。为此,需要将其转换为 byte[]。发送后,我需要将其转换回 Message 对象(在套接字的另一端)。我怎样才能实现这个目标?
I have the following class definition:
public class Message {
private String sender, text;
public Message(String sender, String text) {
this.sender = sender;
this.text = text;
}
}
I would like to be able to send an instance of this Message class over a bluetooth socket. In order to do this, it will need to be converted into a byte[]. After it has been sent, I need to convert it back to a Message object (on the other side of the socket). How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两个可能的答案
Serialized 与 Parcelable
Serialized 相对容易实现,但在内存和 CPU 方面效率不高
http: //developer.android.com/reference/java/io/Serializing.html
Parcelable 实现起来更复杂,但在内存和 CPU 方面更高效
http://developer.android.com/reference/android/os/Parcelable.html
Two possible answers
Serializable vs Parcelable
Serializable relatively easy to implement but not efficient in term of memory and CPU
http://developer.android.com/reference/java/io/Serializable.html
Parcelable more complex to implement but more efficient in term of memory and CPU
http://developer.android.com/reference/android/os/Parcelable.html
查看序列化。
http://developer.android.com/reference/java/io/Serializing.html
Look into serialization.
http://developer.android.com/reference/java/io/Serializable.html
您可以定义一个函数,该函数返回一个
byte[]
并在通过蓝牙发送它之前调用它。字节数组可能类似于{ sendersize, textsize, sender, text }
。还定义一个函数来恢复进程并在另一端调用它。You could define a function, which returns a
byte[]
and just call it before you send it per bluetooth. The byte-array could be like{ sendersize, textsize, sender, text }
. Define also a function which reverts the process and call it on the other side.