问题
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.
回答1:
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.
回答2:
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]
来源:https://stackoverflow.com/questions/27629215/how-can-i-provide-a-scala-companion-objects-class-to-java