简体   繁体   中英

How can I provide a scala companion object's class to Java?

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.

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM