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.intentresolver.ext
18 
19 import android.os.Parcel
20 import android.os.Parcelable
21 import java.lang.reflect.Field
22 
toParcelAndBacknull23 inline fun <reified T : Parcelable> T.toParcelAndBack(): T {
24     val creator: Parcelable.Creator<out T> = getCreator()
25     val parcel = Parcel.obtain()
26     writeToParcel(parcel, 0)
27     parcel.setDataPosition(0)
28     return creator.createFromParcel(parcel)
29 }
30 
getCreatornull31 inline fun <reified T : Parcelable> getCreator(): Parcelable.Creator<out T> {
32     return getCreator(T::class.java)
33 }
34 
getCreatornull35 inline fun <reified T : Parcelable> getCreator(clazz: Class<out T>): Parcelable.Creator<out T> {
36     return try {
37         val field: Field = clazz.getDeclaredField("CREATOR")
38         @Suppress("UNCHECKED_CAST")
39         field.get(null) as Parcelable.Creator<T>
40     } catch (e: NoSuchFieldException) {
41         error("$clazz is a Parcelable without CREATOR")
42     } catch (e: IllegalAccessException) {
43         error("CREATOR in $clazz::class is not accessible")
44     }
45 }
46