1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.ondevicepersonalization.internal.util; 18 19 import java.io.ByteArrayInputStream; 20 import java.io.ByteArrayOutputStream; 21 import java.io.IOException; 22 import java.io.ObjectInputStream; 23 import java.io.ObjectOutputStream; 24 25 /** 26 * Util class to handle different object conversion from/to byte array. 27 * 28 * @hide 29 */ 30 public class ByteArrayUtil { 31 /** serialize an object to byte array. The object need implement Serializable. */ serializeObject(Object input)32 public static byte[] serializeObject(Object input) { 33 try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); 34 ObjectOutputStream out = new ObjectOutputStream(bos)) { 35 out.writeObject(input); 36 return bos.toByteArray(); 37 } catch (IOException e) { 38 throw new IllegalArgumentException("Failed to serialize inputData field", e); 39 } 40 } 41 42 /** Deserialize a byte array to Object. The object need implement Serializable. */ deserializeObject(byte[] bytes)43 public static Object deserializeObject(byte[] bytes) { 44 try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); 45 ObjectInputStream in = new ObjectInputStream(bis)) { 46 return in.readObject(); 47 } catch (IOException | ClassNotFoundException e) { 48 throw new IllegalArgumentException("Failed to deserialize inputData field", e); 49 } 50 } 51 } 52