Question

In Java you can write:

Class<SomeClass> foo = SomeClass.class;

I'm playing around with Scala and want a bit more: I want to get a Method (and its generic type) at compile time, like this:

val foo : Method[...] = SomeClass.class.someMethod

or even:

val foo : Method[...] = someObject.class.someMethod

Is there a way to do something like this in Scala?

Was it helpful?

Solution

With, perhaps, the sole exception of interop against a Java library that demands Method instances, there should never ever be any need to do this in Scala.

If you need to pass a method around for later invocation; then partially apply it to create a FunctionN instance, pass it via a by-name param, or create it directly as a first-class Function in the first case.

If you need to reflect on the Method so that you can circumvent private visibility, perhaps for testing, then you really should refactor your design to avoid that visibility restriction in the first place.

If you're just exploring Scala, and seeing how concepts compare to java. Or if you're unfortunate enough to be stuck with a bad case of interop, then the equivalent construct to SomeClass.class is classOf[SomeClass]. Hopefully you'll never need it :)

OTHER TIPS

For a class:

val classOfClass = classOf[SomeClass]

For an object (the distinction of using getClass is important since otherwise the class of a companion object would be inaccessible):

val classOfObject = SomeClass.getClass

Assuming code like the following:

class SomeClass {
  def someMethod() {}
}

object SomeClass

After this you can use Java reflection operations like Class#getMethod(String,Class<?>...) (assuming someMethod has no parameters):

val method = classOfClass.getMethod("someMethod")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top