scriptInstance from compiled .kts script cannot be used in plugin classloader - ClassCastException because of different classloaders

Answered

I am trying to compile a custom definition of a kotlin script inside my plugin. Closest example outside of a plugin is this main-kts example.

The fact that plugins have their own classloaders is the main thing I am struggling with. I managed to compile the script with this CompilationConfiguration:

// ConfisScriptDefinition is inside a different Jar

// ConfisHost and this code are inside the plugin jar

private val compilationConfiguration = createJvmCompilationConfigurationFromTemplate<ConfisScriptDefinition> {
        jvm {
          // using the plugin's classloader here is what made using my script dependencies possible
            dependenciesFromClassloader(classLoader = ConfisHost::class.java.classLoader, wholeClasspath = true)
      }
  }

Now compilation is succesful, but `BasicJvmScriptingHost().eval(...).returnValue.scriptInstance` cannot be cast to ConfisScriptDefinition

 val scriptInstance = it.returnValue.scriptInstance
 val cast = (scriptInstance as ConfisScriptDefinition) // fails!

In the debugger, `scriptInstance` is definitely a good ConfisScriptDefinition, but I cannot cast it because it is from a different classlaoder.

Is there any way I can compile the kotlin script and make the new scriptInstance with the plugin's PluginClassLoader?

I tried messing with ScriptingHostConfiguraiton (inside the script CompilationConfiguration) the following way but it had the same result:

        hostConfiguration(ScriptingHostConfiguration {
            jvm {
                baseClassLoader.put(ConfisHost::class.java.classLoader)
            }
        }

Thanks in advance!

1 comment
Comment actions Permalink

Fixed by doing:

val scriptongHost = BasicJvmScriptingHost(
ScriptingHostConfiguration {
jvm {
// where ConfisHost is a class inside the jar plugin
baseClassLoader.put(ConfisHost::class.java.classLoader)
}
}
)

Hope this helps someone in the future!

1

Please sign in to leave a comment.