I'm writing a generic encoder/decoder and running into an issue with an extended generic. The idea is that I want to have an abstract Encodeable class that has a "virtual" static method decode which takes a Byte[] and constructs the object, similar to Serializable. (I know this can't really be done in java.) Each class that extends Encodeable will overwrite the encode/decode methods. I then want to use these subclasses of Encodeable generically. Here's an attempt to show what I mean:
public class Encodeable{
// I'd like to write
// static abstract Encodeable decode(Byte[]);
// similar to
// virtual Encodeable decode(Byte[]) = 0;
// in C++, but that seems to be illegal in java
static Encodeable decode(Byte[] buf){return null};
}
public class EncodeableFoo extends Encodeable{
static EncodeableFoo decode(Byte[] buf){
// do actual decoding logic here
}
}
public class Bar<T extends Encodeable>{
public void messageReceived(MessageEvent e){
Byte[] buf = e.getMessage();
T messageObj = T.decode(buf);
// do something with T
}
}
As is, I get an error message like
error: incompatible types
T messageObj = T.decode(objBuf);
^
required: T
found: Encodeable
where T is a type-variable:
T extends Encodeable declared in class EdgeClientHandler
at compile time. But if I change the decode line to
T messageObj = (T) T.decode(objBuf);
it works just fine. Can someone explain this black magic to me? Or, more importantly, give me a better way of writing my generic Bar class such that it knows T has a static method decode (and a non-static method encode)?