java - 我可以从 String (包含我的 Object 引用)转换为 Object 吗?安卓工作室
问题描述
我目前正在通过蓝牙将一个对象(购物)从一个用户发送到另一个用户。当我从服务器电话单击“发送”按钮时,对象购物已正确发送,我通过Log.d(StringNameOfShopping)
但我只能发送bytes[]
数组,将其转换为 int 字节然后创建一个new String(buffer[], offset, bytes)
那么有没有一种方法可以从 String (例如,我的对象 Shopping 参考 : Shopping@bd429a9
)转换为 Shopping 对象?
这是我收听输入和输出的方法。
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
这是我的序列化/反序列化方法(但是我应该把它们放在哪里?在我的 MainActivity 或购物类中?或蓝牙类?
public byte[] serialize(Shopping shopping) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(shopping);
return b.toByteArray();
}
//AbstractMessage was actually the message type I used, but feel free to choose your own type
public static Shopping deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return (Shopping) o.readObject();
}
解决方案
这是行不通的,因为另一部手机无法解析自己内存中的对象。您需要在一部手机上序列化您的对象并在另一部手机上反序列化它。
关于您的编辑:您已决定使用 Java 的序列化机制。为此,您需要Serializable
在 Shopping 中实现接口。这只是一个“标记接口”,即它没有方法,只是表明该类可以与 Java 的序列化工具一起使用。
下一步是使用您要传输serialize
的实例调用该方法。Shopping
这为您提供了一个包含序列化对象的字节数组。现在您可以write
使用此字节数组调用该函数。
在接收端,您需要将整个输入流读入一个字节数组。然后可以传递这个数组deserialize
来获取Shopping
实例。
推荐阅读
- angular - “数字”类型的参数不可分配给“字符串”类型的参数。尝试将值作为 int 时
- python - 创建循环以从数据帧中动态选择行,然后将选定的行附加到另一个数据帧:df.query()
- python - kivy 中超过了最大递归深度,但仅在打包时才超出,而不是在使用 python 开发应用程序时
- json - 在 LinkExtractor 中抓取多个正则表达式似乎不起作用
- c# - C# : Common method/wrapper for methods with different definitions
- r - 移除 ggplot facet strip 标签周围的三边边框
- php - 联系表格 7 wpcf7_before_send_mail 挂钩
- .htaccess - .htaccess 文件未将 HTTP 重定向到 HTTPS
- javascript - P5 组件在移动浏览器中停止更新(但在 PC 浏览器中有效)
- reporting-services - 如何为 SparkLine 数据添加边框?