2010-02-15 42 views
20

如何在Scala中创建一个@interface?我诚实地感到愚蠢的问这个问题,但我找不到任何地方的语法。我知道你可以使用它们,但是你怎么在Scala中定义新的?如何在Scala中定义@interface?

的Java:

public @interface MyAnnotation { } 

斯卡拉:

??? 
+1

我不知道它是否真的值得吗?注释类往往比较小,所以在Scala中编写它们并没有真正的优势。就像枚举一样,把它们写成Java是可以做到的。 – Martin 2011-07-29 11:11:46

回答

25

这个答案是基于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 

有关详情,请参阅第11的Scala Reference 见 “用户定义的注释”,例如:@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

+0

虽然'StaticAnnotation'允许我使用和编译它们,但我怎样才能在运行时查询它们?在Scala中可以找到用'@Retention(RetentionPolicy.RUNTIME)'标记的Java注释,但我找不到在Scala中定义的'StaticAnnotation',即使我使用运行时保留策略来标记它们。 – 2010-02-15 13:13:14

+0

您或其他人能否举例说明如何在Java中定义运行时注释并在Scala中使用它? – Jus12 2011-10-04 07:37:29

+0

Scala 2.9.1中仍存在实现限制。 – mpartel 2012-04-23 23:16:51

4

如果你想创建斯卡拉你应该混合StaticAnnotationClassAnnotation性状的注释。示例代码:

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

如何获取注释中定义的参数\ d?就像在这种情况下参数值“AAA”? – Ashish 2014-09-15 12:17:08

相关问题