Java Serializable Object to Byte Array

后端 未结 12 1302
春和景丽
春和景丽 2020-11-22 03:12

Let\'s say I have a serializable class AppMessage.

I would like to transmit it as byte[] over sockets to another machine where it is rebuil

12条回答
  •  终归单人心
    2020-11-22 03:44

    code example with java 8+:

    public class Person implements Serializable {
    
    private String lastName;
    private String firstName;
    
    public Person() {
    }
    
    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    public String getFirstName() {
        return firstName;
    }
    
    public String getLastName() {
        return lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    @Override
    public String toString() {
        return "firstName: " + firstName + ", lastName: " + lastName;
    }
    }
    
    
    public interface PersonMarshaller {
    default Person fromStream(InputStream inputStream) {
        try (ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
            Person person= (Person) objectInputStream.readObject();
            return person;
        } catch (IOException | ClassNotFoundException e) {
            System.err.println(e.getMessage());
            return null;
        }
    }
    
    default OutputStream toStream(Person person) {
        try (OutputStream outputStream = new ByteArrayOutputStream()) {
            ObjectOutput objectOutput = new ObjectOutputStream(outputStream);
            objectOutput.writeObject(person);
            objectOutput.flush();
            return outputStream;
        } catch (IOException e) {
            System.err.println(e.getMessage());
            return null;
        }
    
    }
    
    }
    

提交回复
热议问题