I'm currently developing a small shared plugin for few projects and the cleanest solution would be if I could read and process a resource file provided by the plugin. However, Java/Kotlin style this.javaClass.getResouce(...)
always returns null
|- src/main/kotlin/myplugin.gradle.kts
|- src/main/resources/file.txt
|- build.gradle.kts
|- settings.gradle.kts
myplugin.gradle.kts
tasks {
val mytask by registering(DefaultTask::class)
mytask {
doLast {
println(this.javaClass.getResource("file.txt")) // Always returns `null`
}
}
}
Is there a clean simple way to access/read a resource file provided by the plugin it self?
PS: The this.javaClass
is org.gradle.api.DefaultTask_Decorated
which does explain why the file is not found. However, it does not help me with reading the actual resource file.
You are writing a plugin in a script file and intending to use it in other projects? I think that is unusual and I am not sure there is a straightforward way to publish such a plugin, let alone a defined way to access resource files.
Instead, write your shared plugin in a regular class file inside its own Gradle project, which Gradle call a binary plugin.
With this approach, your plugin is defined in a class that implements the Plugin<Project>
interface. Then, once you have a class inside a regular compilation you are writing regular code on the JVM and you can access resources included on the classpath in the normal way.
Also, if you are using Kotlin, write this class inside a project with a build.gradle.kts
which applies the kotlin-dsl
plugin and you will have access to many of the Kotlin features you expect in a build script. This plugin also applies the Java Gradle Plugin, giving you the features you need to easily package your plugin.