jeudi 18 juillet 2019

Scala reflection: How to construct object and run its methods given 'String-type' class name and method name?

Given the name of a class, method and parameters from a third party library, how to create an object and invoke its method using scala reflection?

For example, the class name is "org.apache.spark.mllib.clustering.LDA", the method is "setK" and the parameter is 3, how to use scala reflection to construct a LDA object and invoke method? The result should be equivalent to new LDA().setK(3).

In scala reflection document, I found the following code to construct a Person object

val m = ru.runtimeMirror(getClass.getClassLoader)
val classPerson = ru.typeOf[Person].typeSymbol.asClass
val ctor = ru.typeOf[Person].decl(ru.termNames.CONSTRUCTOR).asMethod
val ctorm = cm.reflectConstructor(ctor)
val p = ctorm("Mike")

but what if I have the "Person" instead of the Person class?





Aucun commentaire:

Enregistrer un commentaire