Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cast an object to byteArray

Tags:

java

i have 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 return an object, if the object is byte array, how do i cast the object to byte[]?

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

thanks

like image 838
hkguile Avatar asked Dec 05 '22 16:12

hkguile


1 Answers

By looking at your code:

  • you don't neet do 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
like image 173
Jack Avatar answered Dec 18 '22 13:12

Jack