5

I've got a function:

public static Object receviceSigAndData(Socket s) {
    byte[] data = null;
    try {
        DataInputStream din2 = new DataInputStream(s.getInputStream());
        int sig_len = 0;
        sig_len = din2.readInt();
        byte[] sig = new byte[sig_len];
        din2.readFully(sig);
        int data_len = 0;
        data_len = din2.readInt();
        data = new byte[data_len];
        dsa.update(data);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return (Object) data;
}

The function returns an Object. If the Object is a byte array, how do I cast the Object to byte[]?

byte[] b = (?)receviceSigAndData(socket);

Thanks

bighugedev
  • 379
  • 1
  • 3
  • 11
hkguile
  • 4,235
  • 17
  • 68
  • 139
  • 5
    why not just return a `byte[]` from the method? It seems as though you're unnecessarily casting it to an `Object`. – Jon Egeland May 24 '12 at 03:58

2 Answers2

13

By looking at your code:

  • you don't need to upcast the return value to Object: since it's an upcast, it's implicitly done (a byte[] is statically also an Object)
  • you can easily cast an Object to a byte[] by using a specific downcast:
byte[] a = (byte[]) obj
  • a method like yours that returns an Object is completely pointless, signatures are meant to be useful and informative. Returning an Object is the least informative thing that you can do. If your method is meant to return a byte[], then its return value should be of byte[] type
bighugedev
  • 379
  • 1
  • 3
  • 11
Jack
  • 131,802
  • 30
  • 241
  • 343
7

Here are 2 helper methods to get you to serialize and deserialize byte arrays as objects.

public static Object deserializeBytes(byte[] bytes) throws IOException, ClassNotFoundException
{
    ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bytesIn);
    Object obj = ois.readObject();
    ois.close();
    return obj;
}


public static byte[] serializeObject(Object obj) throws IOException
{
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bytesOut);
    oos.writeObject(obj);
    oos.flush();
    byte[] bytes = bytesOut.toByteArray();
    bytesOut.close();
    oos.close();
    return bytes;
}
george_h
  • 1,562
  • 2
  • 19
  • 37
  • Got here after giving out [https://stackoverflow.com/questions/3677380](https://stackoverflow.com/questions/3677380) reached via [https://stackoverflow.com/questions/9114510](https://stackoverflow.com/questions/9114510) and this totally made tuesday. Tests are now failing, but the use case is now at last working. – 1737973 May 23 '17 at 07:14
  • Pointless. They already are objects, and the OP already has his own serialization and deserialization based on `DataInput/OutputStream`. – user207421 Aug 01 '23 at 00:24