使用Java反射获取嵌套在对象中的类的静态方法

时间:2016-10-23 17:11:27

标签: scala reflection

我想使用Java反射获取嵌套伴随对象中的方法列表。在下面的示例中,这是A.B

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"))

似乎可以在外部伴随对象A上获取方法列表,但不能在嵌套对象上使用。

有没有办法编写一个方法来获取Class[_]并获取同伴对象上定义的所有方法,无论它是否嵌套?

2 个答案:

答案 0 :(得分:1)

classOf[A]classOf[A.B]不是伴随对象的类,因此他们没有这些方法。 A.typeB.type排序,但它们不是Scala中的类类型。正如pedrofurla指出的那样,你可以这样做来作为java Class对象来实现它们:

scala> A.getClass.getDeclaredMethods
res17: Array[java.lang.reflect.Method] = Array(public int A$.bar())

scala> A.B.getClass.getDeclaredMethods
res18: Array[java.lang.reflect.Method] = Array(public int A$B$.foo())

答案 1 :(得分:1)

我提出了以下代码,它假设可以通过将$附加到类名来确定伴侣的类名。

这允许在给定相应类型的类的同伴上调用方法,无论该伴侣是否嵌套:

def getCompanion(clazz: Class[_]) = {
  Class.forName(clazz.getName + "$").getField("MODULE$").get(())
}

def companionMethod(clazz: Class[_], methodName: String) = {
  getCompanion(clazz).getClass.getMethod(methodName).invoke(companion)
}

// Print all companion methods:
println(getCompanion(classOf[A.B]).getMethods.map(_.getName).mkString("\n"))

println(companionMethod(classOf[A], "bar") == 5)
println(companionMethod(classOf[A.B], "foo") == 4)
相关问题