如何在Scala中定义@interface?

时间:2010-02-15 12:08:23

标签: scala annotations

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

爪哇:

public @interface MyAnnotation { }

Scala的:

???

2 个答案:

答案 0 :(得分:26)

这个答案基于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 Reference中的第11节“用户定义的注释” 例如,请参阅:@tailrec

UPDATE 编译器警告说得最好:

>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

Discussion

答案 1 :(得分:5)

如果要在Scala中创建注释,则应混合使用StaticAnnotationClassAnnotation个特征。示例代码:

class MyBaseClass  {}  
class MyAnnotation(val p:String) extends MyBaseClass with StaticAnnotation  {}
@MyAnnotation("AAA")  
class MyClass{}