2
votes

I have a Java code that looks for annotations in static methods of a class.

processor.readStatics( MyClass.class );  // Takes Class<?>

How can I provide the methods of a scala companion object to this function from within scala?

class MyClass {
}
object MyClass {
  def hello() { println("Hello (object)") } 
}

I seems that:

MyClass$.MODULE$.getClass()

should be the answer. However, MyClass$ seems to be missing from scala (in 2.10, at least) and only visible to Java.

println( Class.forName("MyClass$.MODULE$") )

also fails.

2
Have you tried Class.forName("MyClass$MODULE$")? For inner classes no need for additional ..Gábor Bakos
Or Class.forName("MyClass$$MODULE$"), because we have to use $ instead of . for inner classes.Gábor Bakos
Hmm it might be enough to use the class returned by Class.forName(MyClass$). At least it is found with Scala 2.10.3.Gábor Bakos

2 Answers

2
votes

Class name is MyClass$ (with the appropriate package name prepended).

println(Class.forName("MyClass$")) will print out "class MyClass$".

MyClass$.MODULE$ is the instance of the class, referencing the singleton object.

println(MyClass$.MODULE$ == MyClass) will print out "true" even though, when compiling, you will get a warning that this comparison always yields false :)

Note, that none of this works in repl for some reason. You need to actually create a .scala file, compile it with scalac, and run.

So, in java, use MyClass$ to reference the class of MyClass object statically, use MyClass$.MODULE$ to reference the singleton instance of MyClass object, use MyClass$.class or MyClass$.MODULE$.getClass() to reference the class of the singleton object dynamically, use Class.forName("MyClass$") to access it at runtime by name.

1
votes

The shortest and type-safest solution is to simply use

MyClass.getClass

I would have hoped the following to work, but apparently scalac is not happy with it:

classOf[MyClass.type]