dimanche 23 octobre 2016

Get static methods of a class nested in an object using Java reflection

I want to get the list of methods in a nested companion object using Java reflection. This is A.B in the example below.

object A {
  object B {
    def foo: Int = 4
  }

  class B {}

  def bar: Int = 5
}

class A {}

// This works, `bar` is printed.
println(classOf[A].getMethods.map(_.getName).mkString("\n"))

// This doesn't work, `foo` is not printed.
println(classOf[A.B].getMethods.map(_.getName).mkString("\n"))

Seems like getting the list of methods on the outer companion object A works, but not on the nested one.

Is there any way to write a method that would take a Class[_] and get all the methods defined on the companion object whether it's nested or not?





Aucun commentaire:

Enregistrer un commentaire