Reputation: 1604
I want to create a class at runtime
fun generateQueryableClassFromAttributes(
attributes: Map<String, KClass<*>>,
className: String,
){
val classSource = buildString {
append("class $className (val id: String) : Queryable() {\n")
for ((key, value) in attributes) {
append(" var `$key`: ${value.qualifiedName}? = null\n")
}
append("}")
}
val compilationConfiguration = ScriptCompilationConfiguration {
jvm {
dependenciesFromClassContext(ImportQueryable::class, wholeClasspath = true)
baseClass(Queryable::class)
defaultImports(
"com.myclass.Queryable",
"java.util.UUID",
)
}
}
val scriptSource = classSource.toScriptSource(className)
// Evaluate the script
val result = BasicJvmScriptingHost().eval(scriptSource, compilationConfiguration, ScriptEvaluationConfiguration())
val scriptInstance = result.valueOrThrow().returnValue.scriptInstance
val scriptClass = scriptInstance.javaClass.kotlin
println(scriptClass.constructors)
}
I get [fun
(): Name]
as the output of the constructor. I am not able to get the constructor which I have specified which takes a string parameter. scriptClass.members
also returns only the inherited members and not the properties that have been added
How should I go about adding the constructor so that I can see it ? Also how can I set a property ex:
val queryableInstance = queryableClass.primaryConstructor!!.call()
queryableInstance.set("name","Random") where `name` is present in `attributes`
Upvotes: 1
Views: 40