AWS Lambda and Java Reflections (Guava)

Oreex0 :

I am trying to run Guava reflections in my AWS Lambda function but it seems to not work in production..

The Code i am trying to run is supposed to create a Map<String, Class> with class name and class.

Code:

val converterClassMap by lazy {
val cl = ClassLoader.getSystemClassLoader()
ClassPath.from(cl).getTopLevelClasses("converters").asSequence().mapNotNull { it.load().kotlin }
        .filter { it.simpleName?.endsWith("Converter") == true }
        .associateBy( { it.simpleName }, { it } )
}

Running this code locally works perfectly, but running it in production on a lambda return an error where the map is empty.
Key PaginationConverter is missing in the map.: java.util.NoSuchElementException

Has anyone else run into this problem?

Eugene Petrenko :

One more case. You have the

val cl = ClassLoader.getSystemClassLoader()

the line in the code. It means it takes the system classloader to scan for classes.

Try using

class SomeClassFromYouCodeNotALibrary
val cl = SomeClassFromYouCodeNotALibrary::class.java.classLoader

That one will work stable, independent from the number of classloaders, that are used in the application. AWS Lambda runtime may have specific classloaders, for example.

If it does not work, try logging the classloader type and classpath, e.g. println(cl) and println((cl as? URLClassLoader).getURLs().joinToString(", "))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=151281&siteId=1