[英]Get class of Scala object for annotation
I have a use case where I need to do some Java reflection on some Scala objects (don't even ask).我有一个用例,我需要对一些 Scala 对象进行一些 Java 反射(甚至不要问)。 Anyway, I sometimes need to add these objects to an annotation, in Scala.无论如何,我有时需要将这些对象添加到注释中,在 Scala 中。
Here's my (java) annotation:这是我的(java)注释:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
Class<?>[] value();
}
And let's say this is my Scala object:假设这是我的 Scala object:
object Foo{}
In Java, I can reference Foo using my above annotation like this:在 Java 中,我可以像这样使用上面的注释来引用 Foo:
@MyAnnotation(Foo.class)
class SomeClass{}
In Scala, however, I don't see how I can get a type literal from an Object:然而,在 Scala 中,我看不到如何从 Object 中获取类型文字:
@MyAnnotation(Array(classOf[Foo]))
class SomeClass{}
This fails, with error message:这失败了,并显示错误消息:
not found: type Foo未找到:键入 Foo
Is there any way I can reference my Foo object type in a Java annotation?有什么办法可以在 Java 注释中引用我的 Foo object 类型吗? Note that I can't use Foo.getClass
, because that's a method call, not a constant.请注意,我不能使用Foo.getClass
,因为那是方法调用,而不是常量。
Try尝试
@MyAnnotation(Array(classOf[Foo.type]))
class SomeClass
classOf[Foo.type]
is allowed since Scala 2.13.4自 Scala 2.13.4 起允许使用classOf[Foo.type]
https://github.com/scala/scala/pull/9279 https://github.com/scala/scala/pull/9279
https://github.com/scala/bug/issues/2453 https://github.com/scala/bug/issues/2453
In older Scala you can create a class literal manually using a whitebox macro在较旧的 Scala 中,您可以使用白框宏手动创建 class 文字
def moduleClassOf[T <: Singleton]: Class[T] = macro impl[T]
def impl[T: c.WeakTypeTag](c: whitebox.Context): c.Tree = {
import c.universe._
Literal(Constant(weakTypeOf[T]))
}
Usage:用法:
@MyAnnotation(Array(moduleClassOf[Foo.type]))
class SomeClass
https://gist.github.com/DmytroMitin/e87ac170d107093a9b9faf2fd4046bd5 https://gist.github.com/DmytroMitin/e87ac170d107093a9b9faf2fd4046bd5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.