你如何在 Scala 中定义@interface? [英] How do you define an @interface in Scala?

查看:19
本文介绍了你如何在 Scala 中定义@interface?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Scala 中创建 @interface?老实说,我觉得问这个问题很愚蠢,但我找不到这个 anywhere 的语法.我知道你可以使用它们,但你如何在 Scala 中实际定义新的?

How does one create an @interface in Scala? I honestly feel stupid asking that question, but I can't find the syntax for this anywhere. I know that you can consume them, but how do you actually define new ones in Scala?

Java:

public @interface MyAnnotation { }

斯卡拉:

???

推荐答案

这个答案基于 Scala 2.8.

This answer is based on Scala 2.8.

// Will be visible to the Scala compiler, but not in the class file nor at runtime.
// Like RetentionPolicy.SOURCE
final class MyAnnotation extends StaticAnnotation

// Will be visible stored in the annotated class, but not retained at runtime.
// This is an implementation restriction, the design is supposed to support
// RetentionPolicy.RUNTIME
final class MyAnnotation extends ClassfileAnnotation

有关详细信息,请参阅 Scala 参考参见,例如:@tailrec.

For the full details, see section 11 "User Defined Annotations" in the Scala Reference See, for example: @tailrec.

更新编译器警告说得最好:

>cat test.scala
final class MyAnnotation extends scala.ClassfileAnnotation

@MyAnnotation
class Bar

>scalac test.scala
test.scala:1: warning: implementation restriction: subclassing Classfile does not
make your annotation visible at runtime.  If that is what
you want, you must write the annotation class in Java.
final class MyAnnotation extends scala.ClassfileAnnotation

讨论

这篇关于你如何在 Scala 中定义@interface?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆