开发者

Write from Java generic T[] to DataOutput stream?

开发者 https://www.devze.com 2023-01-17 05:03 出处:网络
Given a generic array T[], where T extends java.lang.Number, I would like to write the array to a byte[], using ByteArrayOutputStream. java.io.DataOutput (and an implementation such as java.io.DataOut

Given a generic array T[], where T extends java.lang.Number, I would like to write the array to a byte[], using ByteArrayOutputStream. java.io.DataOutput (and an implementation such as java.io.DataOutputStream appears close to what I need, but there is no generic way to write the elements of the T[] array. I want to do something like

ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(out);

for (T v : getData()) {
  dataOut.write(v); // <== uh, oh
}

but there is no generic <T> void write(T v) method on DataOutput.

Is ther开发者_如何学Goe any way to avoid having to write a whole bunch of isntanceof spaghetti?

Clarification

The byte[] is being sent to a non-Java client, so object serialization isn't an option. I need, for example, the byte[] generated from a Float[] to be a valid float[] in C.


No, there isn't. The instanceof "spaghetti" would have to exist somewhere anyway. Make a generic method that does that:

public <T> void write(DataOutputStream stream, T object) {
   // instanceofs and writes here
}


You can just use an ObjectOutputStream instead of a DataOutputStream, since all Numbers are guaranteed to be serializable.


Regarding to the last edit, I would try this approach (if its ugly or not).

1) Check per instanceof which type you have
2) Store it into a primitive and extract the bytes you need (eg integer) like this (for the first two bytes)

    byte[] bytes = new byte[2];
    bytes[0]=(byte)(i>>8);
    bytes[1]=(byte)i;

3) Send it via the byte[] array
4) Get stuck because different c implementations use different amout of bytes for integer, so nobody can guarantee that the results will equal your initial numbers. e.g. how do you want to handle the 4 byte integer of java with 2 byte integers of c? How do you handle Long?

So...i don't see a way to do, but, im not an expert in this area....

Please correct me if im wrong. ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消