java - 获取用于注释的 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
,因为这是一个方法调用,而不是一个常量。
解决方案
尝试
@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
推荐阅读
- java - 如何为 Maven 项目的资源文件夹中的 fxml 文件设置控制器?
- javascript - 当我传入 json 字符串时,Ajax 不返回 Json
- c++ - 缺少边缘情况的最长回文子串
- c - 使用 C 的链表实现
- amazon-web-services - 使用哪些 AWS 服务来处理 20TB 的 Parquet 文件
- java - 在 Panel 上添加 DrawGraph 而不是在 Frame 上
- android - 如何在listview android中仅更改第二个单元格的背景颜色
- javascript - 有没有办法我的应用程序可以根据设备有不同的行为?
- activemq-artemis - Apache Artemis - libartemis-native-64.so 发货与手动创建 - 都是相同的
- python - 为 .executemany 提供 DataFrame 值以进行 UPDATE