7

I've got a class in which I do some runtime annotation scanning, but it uses the deprecated DexFile APIs which causes a warning to appear in LogCat:

  • W/zygote64: Opening an oat file without a class loader. Are you using the deprecated DexFile APIs?.

I'd like to get rid of this message and use the proper APIs. The docs suggest PathClassLoader, but I don't see how it is equivalent to DexFile in functionality. I can use a PathClassLoader in conjunction with a DexFile instance, and while it does work, it gives me even more warnings and takes longer to scan. I've included the annotation scanner I wrote below for the sake of clarity. If anyone can suggest how to get rid of these warning messages and an alternative to DexFile, so I don't get hit with broken functionality after it's removed, I'd be super appreciative.

class AnnotationScanner {
    companion object {
        fun classesWithAnnotation(
            context: Context,
            annotationClass: Class<out Annotation>,
            packageName: String? = null
        ): Set<Class<*>> {

            return Pair(context.packageCodePath, context.classLoader)
                .letAllNotNull { packageCodePath, classLoader ->
                    Pair(DexFile(packageCodePath), classLoader)
                }
                ?.letAllNotNull { dexFile, classLoader ->
                    dexFile
                        .entries()
                        ?.toList()
                        ?.filter { entry ->
                            filterByPackageName(packageName, entry)
                        }
                        ?.map {
                            dexFile.loadClass(it, classLoader)
                        }
                        ?.filter { aClass ->
                            filterByAnnotation(aClass, annotationClass)
                        }
                        ?.toSet()
                } ?: emptySet<Class<*>>().wlog { "No ${annotationClass.simpleName} annotated classes found" }
        }

        private fun filterByAnnotation(aClass: Class<*>?, annotationClass: Class<out Annotation>): Boolean {
            return aClass
                ?.isAnnotationPresent(annotationClass)
                ?.also {
                    it.ifTrue {
                        Timber.w("Found ${annotationClass.simpleName} on $aClass")
                    }
                }
                ?: false
        }

        private fun filterByPackageName(packageName: String?, entry: String) =
            packageName?.let { entry.toLowerCase().startsWith(it.toLowerCase()) } ?: true
    }
}
Carter Hudson
  • 1,176
  • 1
  • 11
  • 23

0 Answers0