如何为Java提供Scala随播对象的类? [英] How can I provide a scala companion object's class to Java?
问题描述
我有一个Java代码,用于在类的静态方法中查找注释.
I have a Java code that looks for annotations in static methods of a class.
processor.readStatics( MyClass.class ); // Takes Class<?>
如何从scala中向此函数提供scala伴侣对象的方法?
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)") }
}
我似乎是:
MyClass$.MODULE$.getClass()
应该是 answer .但是,scala中似乎缺少MyClass $(至少在2.10中),并且仅对Java可见.
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$") )
也失败了.
推荐答案
类名称为MyClass$
(并带有适当的程序包名称).
Class name is MyClass$
(with the appropriate package name prepended).
println(Class.forName("MyClass$"))
将打印出"Class MyClass $".
println(Class.forName("MyClass$"))
will print out "class MyClass$".
MyClass$.MODULE$
是类的 instance ,引用单例对象.
MyClass$.MODULE$
is the instance of the class, referencing the singleton object.
println(MyClass$.MODULE$ == MyClass)
仍会打印出"true",即使在编译时,您也会收到一条警告,指出该比较总是产生false:)
println(MyClass$.MODULE$ == MyClass)
will print out "true" even though, when compiling, you will get a warning that this comparison always yields false :)
请注意,由于某种原因,这些都不能在repl中起作用.您实际上需要创建一个.scala文件,使用scalac进行编译,然后运行.
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.
因此,在Java中,使用MyClass$
静态引用MyClass
对象的类,使用MyClass$.MODULE$
引用MyClass
对象的单例实例,使用MyClass$.class
或MyClass$.MODULE$.getClass()
引用该类的动态对象,使用Class.forName("MyClass$")
在运行时按名称访问它.
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提供Scala随播对象的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!