java 将对象强制转换为 byteArray

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10730929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:17:19  来源:igfitidea点击:

cast an object to byteArray

java

提问by hkguile

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[]

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

thanks

谢谢

回答by Hyman

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 Objectto a byte[]by using a specific downcast: byte[] a = (byte[])obj
  • a method like yours that returns an Objectis completely pointless, signatures are meant to be useful and informative. Returning an Objectis 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
  • 您不需要将返回值向上转换为Object:因为它是向上转换,所以它是隐式完成的(abyte[]也是静态的Object
  • 您可以使用特定的向下转换轻松地将 an 转换Object为 a byte[]byte[] a = (byte[])obj
  • 像你这样返回 an 的方法Object是完全没有意义的,签名是有用的和提供信息的。返回 anObject是您可以做的信息最少的事情。如果您的方法旨在返回 abyte[]那么它的返回值应该是byte[]类型

回答by george_h

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

这里有 2 个辅助方法,可让您将字节数组序列化和反序列化为对象。

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;
}