reflection - Scala Method Mirror return Type is always Any -
i new scala. how solve problem method mirror returns any?
class abc{ def getstring(): string = { return "a,b,c"; } } //somewhere in project val ru = scala.reflect.runtime.universe val mirror = ru.runtimemirror(getclass.getclassloader); val c = class.forname("abc"); val classsymbol = mirror.classsymbol(c); val classtype = classsymbol.totype; val im = mirror.reflect(c.newinstance()) val _method_ = classtype.declaration(ru.newtermname("getstring")).asmethod; val method = im.reflectmethod(_method_); println(method()); //this prints "a,b,c" println(method().length()); // error, value length not member of
can proper function returns proper object instead of any? thank you! if method mirror cannot return proper object(like string), point of method mirror?
there no way runtime reflection return objects proper static types because static types applicable @ compilation time (hence static types); in order enforce dynamically created object have desired static type, have manual cast whatever type need , know returned @ runtime.
so either:
val ret = method().asinstanceof[string].length
or
val typedmethod = () => method().asinstanceof[string] val ret = typedmethod().length // ret 5
unfortunately there seems no way cast method
object appropriate function type directly (unless i'm missing here):
method.asinstanceof[() => string]
will raise @ runtime
java.lang.classcastexception: scala.reflect.runtime.javamirrors$javamirror$javavanillamethodmirror cannot cast scala.function0
and
(method.apply _).asinstanceof[() => string]
will raise @ runtime
java.lang.classcastexception: test$$anonfun$1 cannot cast scala.function0
Comments
Post a Comment