1 /*
2 * Copyright 2025 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 androidx.appfunctions.internal
18
19 import android.os.Build
20 import androidx.annotation.RequiresApi
21
22 /**
23 * Finds the implementation of the given [Class].
24 *
25 * @param suffix the suffix used with the [Class] name to identify the implementation class. Then,
26 * use the `_Impl` as suffix. Default value is `_Impl`.
27 * @return the implementation instance.
28 * @throws RuntimeException if unable to find the implementation class.
29 */
30 @RequiresApi(Build.VERSION_CODES.S)
findImplnull31 internal fun <T : Any> Class<T>.findImpl(prefix: String, suffix: String): T {
32 val fullPackage = this.packageName
33 val name = this.canonicalName
34 requireNotNull(name)
35
36 val postPackageName = name.substring(fullPackage.length + 1)
37 val implName = "$prefix$postPackageName$suffix"
38 return try {
39 val fullClassName = "$fullPackage.$implName"
40 @Suppress("UNCHECKED_CAST")
41 val aClass = Class.forName(fullClassName, true, this.classLoader) as Class<T>
42 aClass.getDeclaredConstructor().newInstance()
43 } catch (e: ClassNotFoundException) {
44 throw RuntimeException(
45 "Cannot find implementation for ${this.canonicalName}. $implName does not " +
46 "exist. Is AppFunction annotation processor correctly configured?",
47 e,
48 )
49 } catch (e: IllegalAccessException) {
50 throw RuntimeException("Cannot access the constructor ${this.canonicalName}", e)
51 } catch (e: InstantiationException) {
52 throw RuntimeException("Failed to create an instance of ${this.canonicalName}", e)
53 }
54 }
55