Drew H
Drew H

Reputation: 4739

Reflection in scala. Invoke method?

Class<?> clazz = loadClass( "Test" );
Method printSomething = clazz.getDeclaredMethod( "printSomething" );
printSomething.invoke( clazz );

I'm trying to figure out how to do this in Scala. I'm guessing I'm missing something simple with the way Scala handles reflection.

val clazz = loadClass("Test")
val printSomething = clazz.getDeclaredMethod("printSomething")

printSomething.invoke(clazz)

My main question: Is the Any object the same as Class<?> in Java?

Upvotes: 1

Views: 3024

Answers (1)

Nikita Volkov
Nikita Volkov

Reputation: 43309

Any is not the same as Class<?> in Java.

The Any type is a Scala alternative to Java's Object with extensions: in difference to Java's Object it is a supertype to literally everything in Scala, including primitives.

The Class[_] (short for Class[Any]) is the same type as Java's Class<?>, namely it is the way Java's Class<?> is presented in Scala. Instances of type Class in Scala as much as in Java provide the basic reflection capabilities over the type provided as its generic parameter. I.e. an instance of Class[Something] provides the standard Java's reflection API over class Something. You can use it the same way you do in Java. To get that instance you call the standard method classOf[Something] or instanceOfSomething.getClass.

Extended reflection capabilities primarily targeted at the solution of the type erasure issue are coming with Scala 2.10, pretty stable snapshot versions of which you can always download. This extended API is provided thru the object scala.reflect.runtime.Mirror. There's not much documentation on it in the internet yet, but you can find some decent information here on StackOverflow.

Upvotes: 4

Related Questions