首页 > 解决方案 > 获取用于注释的 Scala 对象类

问题描述

我有一个用例,我需要对一些 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 中,我看不到如何从 Object 中获取类型文字:

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

这失败了,并显示错误消息:

未找到:类型 Foo

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

标签: javascalareflectionannotations

解决方案


尝试

@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 中,您可以使用白盒宏手动创建类文字

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


推荐阅读