How to get a byte[] object from another class object in J2ME?

arrays, java, java-me

Solution

Is it possible to get a byte[] object from any other class type ?

Some classes may implement a simular service.

Is it possible to get a byte[] object from a user-defined class object ?

Not without you writing the conversion yourself.

Example how to do it yourself (just note that the `DataOutputStream` handles the conversion, for example which byte order that is used):

ByteArrayOutputStream out = new ByteArrayOutputStream();
{
    // conversion from "yourObject" to byte[]
    DataOutputStream dos = new DataOuputStream(out);
    dos.writeInt(yourObject.intProperty);
    dos.writeByte(yourObject.byteProperty);
    dos.writeFloat(yourObject.floatProperty);
    dos.writeChars(yourObject.stringProperty);
    dos.close();
}
byte[] byteArray = out.toByteArray();

Problem

I know that in J2ME I can get a `byte[]` object from a String object by using the `getBytes()` method. My question is : is it possible to get a `byte[]` object from any other `class type` ? In addition : is it possible to get a `byte[]` object from a user-defined class object ?

Original source