vendredi 9 décembre 2016

java cast byte[] to class at runtime

Perhaps I am just missing a feature in Java. I have messages which arrive through a com port as byte[]. I need them to automatically become the correct class so the application code does not need to worry about converting them. In addition, there are 1000's of these messages with the ability to add more later, so I want to be able to add subclasses to the message class and have the automatic part work without changes by the developer.

public class Msg {
  public final int id;
  public byte[] payload;
  public Msg(byte[] bytes) {
    this.id = ((byte[0]<<8)&xFF00) + (byte[1]&0xFF);
    payload = new byte[bytes.length-2];
    for (int i=2; i<bytes.length; i++)
       payload[i-2] = bytes[i];  
  }
}
public class AbcMsg extends Msg {
  public static int id = 0x1234;
  public AbcMsg(byte[] bytes) {
    super(bytes);
    if (this.id != ((byte[0]<<8)&xFF00) + (byte[1]&0xFF))
      throw MsgException;
  }
  public int Field1() { return (int) payload[1] };
}

public class Test {
  public Msg toMsg(byte[] bytes){
     // I have code that creates a Map of Msg Id to correct constructor.
    msgId = ((byte[0]<<8)&xFF00) + (byte[1]&0xFF));
    Constructor con = msgIdtoConstructorMap.get(msgId);
    Object msg = con.newInstance(bytes);
    return msg;  // <======================= FAIL type mismatch Object to Msg
  }
  public static void main() {
     byte[] message;
     Msg msg;
     while (true) {
        msgBytes = ComPort.getline();  // reads a full message.
        msg = toMsg(msgBytes);
     }
  }
}


I hope that gives you the idea. The issue is the constructor returns Object and I need it to be my superclass Msg. Or perhaps there is another easier way for this to be done?





Aucun commentaire:

Enregistrer un commentaire