Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 218
user48956 Avatar asked Oct 18 '25 21:10

user48956


1 Answers

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.

like image 70
Dima Avatar answered Oct 21 '25 12:10

Dima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!