java对象转byte
时间: 2023-09-07 18:18:11 浏览: 153
JAVA转byte[]为int,long,double
4星 · 用户满意度95%
在Java中,将对象转换为字节数组有多种方法。一种常见的方法是实现Java自带的Serializable接口,并使用ObjectInputStream和ObjectOutputStream来进行序列化和反序列化。可以使用以下方法将对象转换为字节数组:
```
private byte[] objectToByte(Object obj) {
byte[] bytes;
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
bytes = bo.toByteArray();
bo.close();
oo.close();
} catch(Exception ae) {
throw ae;
}
return bytes;
}
```
另一种方法是使用ByteBuffer类,该类提供了一种方便的方式来操作字节数据。您可以使用ByteBuffer将对象的字段按照特定的顺序写入字节缓冲区,并使用array()方法将字节缓冲区转换为字节数组。然后,您可以使用相同的字节缓冲区将字节数组转换回对象。以下是一个示例:
```
public class Student {
byte height;
int age;
long phone;
}
public static void main(String[] args) {
Student student = new Student();
student.height = (byte) 185;
student.age = 23;
student.phone = 18380330237L;
// 对象序列化到字节数组
ByteBuffer byteBuffer = ByteBuffer.allocate(100).order(ByteOrder.BIG_ENDIAN);
byteBuffer.put(student.height);
byteBuffer.putInt(student.age);
byteBuffer.putLong(student.phone);
byte[] array = byteBuffer.array();
// 字节数组序列化到对象
byteBuffer = ByteBuffer.allocate(100).order(ByteOrder.BIG_ENDIAN);
byteBuffer.put(array);
byteBuffer.position(0);
Student student2 = new Student();
student2.height = byteBuffer.get();
student2.age = byteBuffer.getInt();
student2.phone = byteBuffer.getLong();
}
```
此外,还有一些第三方工具可用于更方便地将字节转换为Java对象,例如magic-byte库。您可以在GitHub上找到该库的详细信息和使用方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [JAVA对象转字节数组](https://blog.csdn.net/jioulongzi/article/details/122101214)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文