Object转byte[];byte[]转Object

时间:2025-04-24 07:49:47
package ; import ; import ; import ; import ; import ; import ; public class ObjectAndByte { /** * 对象转数组 * @param obj * @return */ public byte[] toByteArray (Object obj) { byte[] bytes = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); (obj); (); bytes = (); (); (); } catch (IOException ex) { (); } return bytes; } /** * 数组转对象 * @param bytes * @return */ public Object toObject (byte[] bytes) { Object obj = null; try { ByteArrayInputStream bis = new ByteArrayInputStream (bytes); ObjectInputStream ois = new ObjectInputStream (bis); obj = (); (); (); } catch (IOException ex) { (); } catch (ClassNotFoundException ex) { (); } return obj; } public static void main(String[] args) { TestBean tb = new TestBean(); ("daqing"); ("1234567890"); ObjectAndByte oa = new ObjectAndByte(); byte[] b = (tb); System.out.println(new String(b)); System.out.println("======================================="); TestBean teb = (TestBean) (b); System.out.println(()); System.out.println(()); } }