I am trying to get the reflected runtime method in an instance but it is not shown in the decls result:
val foo: AnyRef = new Object {
def bar = 1
}
typeOf[foo.type].decls //Does not contain bar method
I tried to use Java reflection class and it works:
foo.getClass.getDeclaredMethods //It contains bar method
But I prefer to work with MethodSymbols and Scala Type than Java Class and Method reflection. How can I get the reflected MethodSymbol?
I want an method to look up an object passed as AnyRef for a method bar and call it. Something like below:
def getBarMethodFromObj(obj: AnyRef): MethodSymbol = {
//typeOf(obj).decl(TermName("bar")) this doesn't work
}
I cannot use trait because bar can have different argument and return types and numbers. As Scala does not support varadic generic arguments, I plan to use reflection to find the method and call, but this cannot be done in Scala as well. I am currently use Java solution:
val bar = foo.getClass.getDeclaredMethods.find(_.getName == "bar")
bar.invoke(foo, params: _*)
However Java reflection does not retain generic types as it creates problem for List and Map, etc. So I want to know if I can implement this in Scala, or is there any coming solution
foo.bardoesn't compile either. The valuefoois of typefoo.type, which is subtype ofAnyRef, andAnyRefdoes not have a methodbar. ThetypeOf[foo.type]gizmo contains only the information that can be inferred at compile time, and at compile time, there is nothing that indicates thatfoohas a methodbar, from the compiler's perspective. - Andrey Tyukin