简体   繁体   中英

How to encode an Java Object(Class) and decode it again?

I want to make a bridge between two Java Engines and me don't want to use any data storages like MySql or Files. So I think the best option is to create a SocketServer and send the given Information. But my problem is that I don't know how to transfer an by the variable type itself. I want to send it directly from Field to Field so I have the exactly object on the other side. But I don't what to send a special Object or Class I want Something which is able to transfer every class.

Your data transfer object should implement Serializable interface to have any of its state serialized and deserialized. An example:

public class MyDTO implements Serializable {

  private String field1;
  private int field2;

  // getters and setters
}

You can then write and read the object on the sockets. Example:

// writing

socket.getOutputStream.write(myDtoObject);

// reading
MyDTO dto = (MyDTO) socket.getInputStream.readObject();

I highly recommend reading through the Javadoc for more info about the Serializable interface: https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM