Java Serializable Object to Byte Array

后端 未结 12 1310
春和景丽
春和景丽 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:30

    The best way to do it is to use SerializationUtils from Apache Commons Lang.

    To serialize:

    byte[] data = SerializationUtils.serialize(yourObject);
    

    To deserialize:

    YourObject yourObject = SerializationUtils.deserialize(data)
    

    As mentioned, this requires Commons Lang library. It can be imported using Gradle:

    compile 'org.apache.commons:commons-lang3:3.5'
    

    Maven:

    
    
        org.apache.commons
        commons-lang3
        3.5
    
    

    Jar file

    And more ways mentioned here

    Alternatively, the whole collection can be imported. Refer this link

提交回复
热议问题