There is a client-server that communicate with each other with silverized objects. The question arose how to determine which object came to the server in order to correctly recognize it?

A client who randomly sends 3 variants of an object

List <Integer> lInt = new ArrayList<>(); List <String> lStr= new ArrayList<>(); List <Object> lObj= new ArrayList<>(); ObjectOutputStream sOut = new ObjectOutputStream(socket.getOutputStream()); sOut.writeObject(lInt); sOut.writeObject(lStr); sOut.writeObject(lObj); 

The server that receives the object and deserializes it. But how can I understand what kind of object came in so that it can be projected then for example: lInt = (List "Integer") obj?

 List <Integer> lInt = new ArrayList<>(); List <String> lStr= new ArrayList<>(); List <Object> lObj= new ArrayList<>(); ServerSocket serversocket = new ServerSocket(7800); Socket socket = serversocket.accept(); ObjectInputStream sIn = new ObjectInputStream(socket.getInputStream()); Object obj = null; while ((obj = sIn.readObject())!=null){ lInt = (List <Integer>)obj; ////Ошибка Ссли ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ Π½Π΅ List <Integer> } 

    1 answer 1

    Because it is also necessary to transfer the data type.

    I recommend creating a base class for queries, for example:

     public class MyRequest{ public static enum RequestType {int, string, obj}; private RequestType mType; private Object mData; public MyRequest(RequestType type, Object data){ mType = type; mData = data; } public RequestType getRequestType(){ return mType; } public Object getData(){ return mData; } } 

    Then it will be like this:

     MyRequest intRequest = new MyRequest(RequestType.int, new ArrayList<>()); ObjectOutputStream sOut = new ObjectOutputStream(socket.getOutputStream()); sOut.writeObject(intRequest ); 

    And on the server:

     List <Integer> lInt; MyRequest request; ServerSocket serversocket = new ServerSocket(7800); Socket socket = serversocket.accept(); ObjectInputStream sIn = new ObjectInputStream(socket.getInputStream()); Object obj = null; while ((obj = sIn.readObject())!=null){ request = (MyRequest)obj; // ΠΏΡ€ΠΈΠ²ΠΎΠ΄ΠΈΡ‚ сначала ΠΊ Ρ‚ΠΈΠΏΡƒ Π±Π°Π·ΠΎΠ²ΠΎΠ³ΠΎ рСквСста switch(request.getRequestType()){ // Π° ΠΏΠΎΡ‚ΠΎΠΌ Π² зависимости ΠΎΡ‚ Ρ‚ΠΈΠΏΠ° запроса ΠΏΡ€ΠΈΠ²ΠΎΠ΄ΠΈΠΌ ΠΊ Π½ΡƒΠΆΠ½ΠΎΠΌΡƒ классу case RequestType.int: lInt = (List <Integer>)request.getDate(); break; } } 
    • Thank! What did not think of it before - user200303