[英]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. 我有一个Java代码,用于在类的静态方法中查找注释。
processor.readStatics( MyClass.class ); // Takes Class<?>
How can I provide the methods of a scala companion object to this function from within scala? 如何从scala中向此函数提供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. 但是,scala中似乎缺少MyClass $(至少在2.10中),并且仅Java可见。
println( Class.forName("MyClass$.MODULE$") )
also fails. 也失败了。
Class name is MyClass$
(with the appropriate package name prepended). 类名是MyClass$
(带有适当的包名)。
println(Class.forName("MyClass$"))
will print out "class MyClass$". println(Class.forName("MyClass$"))
将打印出“ class MyClass $”。
MyClass$.MODULE$
is the instance of the class, referencing the singleton object. MyClass$.MODULE$
是类的实例 ,引用单例对象。
println(MyClass$.MODULE$ == MyClass)
will print out "true" even though, when compiling, you will get a warning that this comparison always yields false :) 即使在编译时, println(MyClass$.MODULE$ == MyClass)
也会打印出“ true”,尽管您会收到一条警告,指出该比较总是产生false :)
Note, that none of this works in repl for some reason. 请注意,由于某种原因,这些都不能在repl中起作用。 You need to actually create a .scala file, compile it with scalac, and run. 您实际上需要创建一个.scala文件,使用scalac进行编译,然后运行。
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. 因此,在Java中,使用MyClass$
静态引用MyClass
对象的类,使用MyClass$.MODULE$
引用MyClass
对象的单例实例,使用MyClass$.class
或MyClass$.MODULE$.getClass()
引用单例对象的动态类,使用Class.forName("MyClass$")
在运行时按名称访问它。
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: 我本来希望以下方法能起作用,但显然scalac
对此并不满意:
classOf[MyClass.type]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.