获取 class 个用于注解的 Scala 对象

Get class of Scala object for annotation

我有一个用例,我需要对一些 Scala 对象进行一些 Java 反射(甚至不要问)。无论如何,我有时需要在 Scala 中将这些对象添加到注释中。

这是我的 (java) 注释:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
   Class<?>[] value();
}

假设这是我的 Scala 对象:

object Foo{}

在 Java 中,我可以像这样使用上面的注释来引用 Foo:

@MyAnnotation(Foo.class)
class SomeClass{}

但是,在 Scala 中,我不知道如何从对象中获取类型文字:

@MyAnnotation(Array(classOf[Foo]))
class SomeClass{}

失败,错误消息:

not found: type Foo

有什么方法可以在 Java 注释中引用我的 Foo 对象类型?请注意,我不能 use Foo.getClass,因为那是方法调用,而不是常量。

尝试

@MyAnnotation(Array(classOf[Foo.type]))
class SomeClass

classOf[Foo.type] 自 Scala 2.13.4

起被允许

https://github.com/scala/scala/pull/9279

https://github.com/scala/bug/issues/2453


在较旧的 Scala 中,您可以使用 whitebox

手动创建 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]))
}

用法:

@MyAnnotation(Array(moduleClassOf[Foo.type]))
class SomeClass

https://gist.github.com/DmytroMitin/e87ac170d107093a9b9faf2fd4046bd5