Reputation: 41
I am new to Scala. So how could I solve the problem that method mirror always returns Any?
class ABC{
def getString(): String = {
return "a,b,c";
}
}
//somewhere in the 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 is not a member of any
Can I get the proper function that returns the proper object instead of Any? Thank you! If the method mirror cannot return the proper object(Like String), then what is the point of method mirror?
Upvotes: 2
Views: 620
Reputation: 38247
There is no way for runtime reflection to return objects with proper static types because static types are only applicable at compilation time (hence static types); in order to enforce a dynamically created object to have the desired static type, you have to do a manual cast to whatever type you need and know will be returned at runtime.
So either:
val ret = method().asInstanceOf[String].length
or
val typedMethod = () => method().asInstanceOf[String]
val ret = typedMethod().length // ret will be 5
Unfortunately there seems to be no way to cast the method
object to the appropriate function type directly (unless I'm missing something here):
method.asInstanceOf[() => String]
will raise at runtime
java.lang.ClassCastException: scala.reflect.runtime.JavaMirrors$JavaMirror$JavaVanillaMethodMirror cannot be cast to scala.Function0
and
(method.apply _).asInstanceOf[() => String]
will raise at runtime
java.lang.ClassCastException: test$$anonfun$1 cannot be cast to scala.Function0
Upvotes: 1