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

橙三吉。 提交于 2020-01-04 16:57:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!