Home > Enterprise >  Load kotlin resource from outside a class
Load kotlin resource from outside a class

Time:08-21

I have a couple of top level functions in my Kotlin code:

fun getSomeText(path: String): String? {
    // return contents of the path relative to src/main/resources/some_dir
}

Where this function simply returns the content of the file in src/main/resources/some_dir/path. I don't have a class to access ::class.java.getResource from. I've seen people using {}::class.java.getResource, but this creates a new object whenever a resource is accessed. Is there a built-in way to access a resource from a static context in kotlin?

CodePudding user response:

If you do not want to create an anomymous class, and (as I understand from your comment) the given path should always be relative to a given path "/my_custom_dir", you can for instance use Any's class's class to get the resource from that class:

fun getSomeText(path: String): String? =
    Any::class::class.java.getResource("/my_custom_dir/$path").readText()

As far as I can tell, it does not work with just Any::class, but with Any::class::class.

Further, please note that the leading slash in the path makes sure that you do look for a path relative to your classpath's root and not relative to the given class's location.


If you can be sure that the function is called from inside a class, an alternative would be to use the class of the caller like this:

fun <T : Any> T.getSomeText(path: String): String? =
    this::class.java.getResource("/my_custom_dir/$path").readText()

From inside any class this function can just be called like getSomeText(...) without the need to explicitly specify the receiver. When you take away the /my_custom_dir/ part of the path, this function has the advantage that you can also use it to load some resource relative to the calling class.

  • Related