Search code examples
javagenericsprotocol-buffersgeneric-programming

how can i make Generic function's params as protobuffer in java?


I want to make a function to handle different type of protocal buffer variable, which all need to call api function of protobuffer. code like this:

public <T > void Send(T s) {
    if (mode == "PUB") {
      sock.send(s.toByteArray(), 0);   // error here, toByteArray is an api function in protocal buffer
    } else if (mode == "REQ") {
      sock.send(s.toByteArray(), 0); 
      byte[] rs = sock.recv(0);
      System.out.println("recv ack " + Arrays.toString(rs));
    } else {
      System.out.println("Unknown mode " + mode);
      System.exit(1);
    }   
  }

  public <T> void Recv(T t) throws InvalidProtocolBufferException {
    if (m_mode == "SUB") {
      t = T.parseFrom(m_sock.recv()); // error here
    } else if (m_mode == "REP") {
      T er = T.parseFrom(m_sock.recv());
      m_sock.send(er.getReqid());
      return er; 
    } else {
      System.out.println("Unknown mode " + m_mode);
      System.exit(1);
      return T.parseFrom(m_sock.recv());
    }   
  }

That didnt work for me, bc s.toByteArray() and T.parseFrom() is not found, can anyone help on this? I am a c++ developer, learning java recently, can java support generic function, and handle the generic params according to my function declaration? Thanks


Solution

  • All your generated protobuf classes extend the type com.google.protobuf.GeneratedMessage and that type has the method toByteArray (which it inherited from com.google.protobuf.AbstractMessageLite)

    Just declare your method as :

    public void Send(com.google.protobuf.GeneratedMessage s) {
    

    or

    public void Send(com.google.protobuf.AbstractMessageLite s) {
    

    You don't need generics - you can depend on the inheritance type hierarchy.

    Also note: never compare Strings with == in Java like you are doing in your posted code. Use the equals method instead; == returns false if the Strings have the same content but are different instances of the String class.