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?
Anyis not the same asClass<?>in Java.The
Anytype is a Scala alternative to Java’sObjectwith extensions: in difference to Java’sObjectit is a supertype to literally everything in Scala, including primitives.The
Class[_](short forClass[Any]) is the same type as Java’sClass<?>, namely it is the way Java’sClass<?>is presented in Scala. Instances of typeClassin Scala as much as in Java provide the basic reflection capabilities over the type provided as its generic parameter. I.e. an instance ofClass[Something]provides the standard Java’s reflection API over classSomething. You can use it the same way you do in Java. To get that instance you call the standard methodclassOf[Something]orinstanceOfSomething.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.