hlepme
hlepme

Reputation: 97

Load class from kotlin script file in java

Groovy has a GroovyClassLoader with which a groovy class can be loaded into your java application with GroovyClassLoader.parseClass(String script) and then instantiated at a later time and it's method invoked.

Is there a way to do this with kotlin script files (.kts)?

I know I can use jsr223 to evaluate a script file with ScriptEngine.eval(String script) which uses KotlinJsr223JvmLocalScriptEngineFactory , however calling eval over a script which is simply a class declaration, returns null and I can't access that class.

I have added the correct dependencies and kotlin script engine factory is correctly loaded (I can see it in the result of new ScriptEngineManager().getEngineFactories()), I just get null as a result of eval. Assuming that's because the script itself doesn't really return anything, just define a class. This is what the script file I'm trying to load looks like:

package scripts

import com.example.SomeJavaInterface
import com.example.SomeArg
import com.example.SomeReturnValue

class TestScript : SomeJavaInterface {
    override fun someMethod(SomeArg arg): SomeReturnValue {
        return SomeReturnValue()
    }
}

I'm using kotlin-stdlib, kotlin-compiler and kotlin-script-util version 1.2.41.

Is this not achievable with kotlin scripts?

Upvotes: 1

Views: 1526

Answers (1)

Ryan Benasutti
Ryan Benasutti

Reputation: 51

You can return the class itself from the script. For example, the last line of your script could be TestScript::class. This gives you a KClass which you can then instantiate. To give you a real-world example, you can see how I instantiate the class I get from the script here.

Upvotes: 3

Related Questions