@@ -10,20 +10,21 @@ import kotlinx.coroutines.*
1010import java.lang.reflect.*
1111import kotlin.coroutines.*
1212
13- private val getter by lazy {
14- try {
15- Thread ::class .java.getDeclaredMethod(" getUncaughtExceptionPreHandler" ).takeIf {
16- Modifier .isPublic(it.modifiers) && Modifier .isStatic(it.modifiers)
17- }
18- } catch (e: Throwable ) {
19- null /* not found */
20- }
21- }
22-
2313@Keep
2414internal class AndroidExceptionPreHandler :
25- AbstractCoroutineContextElement (CoroutineExceptionHandler ), CoroutineExceptionHandler
26- {
15+ AbstractCoroutineContextElement (CoroutineExceptionHandler ), CoroutineExceptionHandler , Function0 <Method ?> {
16+
17+ private val preHandler by lazy(this )
18+
19+ // Reflectively lookup pre-handler. Implement Function0 to avoid generating second class for lambda
20+ override fun invoke (): Method ? = try {
21+ Thread ::class .java.getDeclaredMethod(" getUncaughtExceptionPreHandler" ).takeIf {
22+ Modifier .isPublic(it.modifiers) && Modifier .isStatic(it.modifiers)
23+ }
24+ } catch (e: Throwable ) {
25+ null /* not found */
26+ }
27+
2728 override fun handleException (context : CoroutineContext , exception : Throwable ) {
2829 /*
2930 * If we are on old SDK, then use Android's `Thread.getUncaughtExceptionPreHandler()` that ensures that
@@ -38,8 +39,8 @@ internal class AndroidExceptionPreHandler :
3839 if (Build .VERSION .SDK_INT >= 28 ) {
3940 thread.uncaughtExceptionHandler.uncaughtException(thread, exception)
4041 } else {
41- (getter ?.invoke(null ) as ? Thread .UncaughtExceptionHandler )
42+ (preHandler ?.invoke(null ) as ? Thread .UncaughtExceptionHandler )
4243 ?.uncaughtException(thread, exception)
4344 }
4445 }
45- }
46+ }
0 commit comments