Is it possible to test the type in a generic function? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this questionI would like to make a generic function that deserializes a byte array into a type specified by the caller. I feel that a really intuitive way to call such a function would look something like:
byte[255] myData = [...]
String myUnserializedString = new Packet<String>(myData).unpack();
byte[4] myInt = [...]
int myUnserializedInt = new Packet<Integer>(myInt).unpack();
As a user, 开发者_JAVA技巧this is the kind of interface I'd like to be offerred. The problem is that (obviously) each type has to be unserialized in a different way. This means that the unpack() method has to perform some kind of reflexive test to choose the right way to interpret the raw bytes.
After trying for a little while to write a prototype for such a class, I am beginning to feel that Generics may not be the right tools for that kind of design.
Are they?
You could define Packet as an interface, and have one implementation for each type of data.
public interface Packet<T> {
T unpack(byte[] data);
}
public final class StringPacket implements Packet<String> {
public String unpack(byte[] data) {
// Implementation...
}
}
// Similar classes for other types...
Generics are not providing any real type safety here, but it could provide some casting convenience. However, the obvious way to do this is to have the unpack method do all the work:
public <T> T unpack(Class<T> klass) {
return klass.cast(unpackedData);
}
And call it like this:
new Packet(myData).unpack(String.class);
Even if you could twist generics into getting it done the way you want (I think you can with an unsafe cast, which is all Class.cast is doing anyway), this is the more standard idom and avoids you doing your own unsafe casting. Either way, you are saying that the client knows the type, as it sets the Generic parameter in your example.
If they have to be handled in a different way, then Packet is not truly generic!
There's nothing wrong with
class StringPacket extends Packet {
// ...
}
or
class StringPacket implements Receivable, Sendable {
// ...
}
Why not?
class Packet<T> {
private byte[] bytes;
// consructor here
public T unpack() {
(T) readObject(bytes);
}
}
readObject(..)
can rely on ObjectInputStream
精彩评论