shakedzy shakedzy - 3 months ago 15
Scala Question

Scala: reflection with different argument types

I'm trying to use reflection, pretty much in the same way seen in the answer of this question. The thing is that my code looks like this:

class A {
def query1(arg: Int): String = { Some code }
def query2(arg: String): String = { Some code }
def query3(): String = { Some code }
}

object A {
def apply(query: String, arg: Any): String = {
val a = new A
val method = a.getClass.getMethod(query,arg.getClass)
method.invoke(a,arg)
}
}


But this cannot be compiled, and I get an error:

type mismatch; found: Any, required: Object


Any ideas how can I make this work?

Answer
object A {
  def apply(query: String, arg: AnyRef): String = {
    val a = new A
    val method = a.getClass.getMethod(query, arg.getClass)
    method.invoke(a, arg).toString
  }
}

The problem here is that Any can also be of a primitive type, namely Int, Short, Long and so on, which are not objects in Java, so if the invoke method expects Object, you need a compile time guarantee everything you supply to that method will also be an Object

Comments