繁体   English   中英

注解的Scala类型别名

[英]Scala Type aliases for annotations

在我的代码的很多地方,三个注释一起出现:

@BeanProperty
@(SpaceProperty @beanGetter)(nullValue="0")

其中nullValue="0"是注释SpaceProperty的参数。

是否可以为@BeanProperty @(SpaceProperty @beangetter)定义一个类型别名?

我能做的最好的事情是:

type ScalaSpaceProperty = SpaceProperty @beanGetter

@BeanProperty
@(ScalaSpaceProperty)(nullValue = "0")

是否有可能为两个注释定义类型别名,其中参数应用于最后一个注释?

否。我认为,您可以在Scala 2.10中编写宏来执行此操作(但是该文档目前不可用,因此无法检查)。

我知道的类型别名注释的唯一示例是在Scaladoc中 以下是相关部分:

object ScalaJPA {
  type Id = javax.persistence.Id @beanGetter
}
import ScalaJPA.Id
class A {
  @Id @BeanProperty val x = 0
}

这等效于在类A中编写@(javax.persistence.Id @beanGetter) @BeanProperty val x = 0

type声明只能处理类型。 换句话说,您不能在类型别名中提供实例信息。

一种替代方法是尝试扩展注释。 下面,出于说明目的,我创建了一个假设的SpaceProperty

scala> import scala.annotation._; import scala.annotation.target._; import scala.reflect._;
import scala.annotation._
import scala.annotation.target._
import scala.reflect._

scala> class SpaceProperty(nullValue:String="1",otherValue:Int=1) extends Annotation with StaticAnnotation

scala> class SomeClass(@BeanProperty @(SpaceProperty @beanGetter)(nullValue="0") val x:Int)
defined class SomeClass

scala> class NullValueSpaceProperty extends SpaceProperty(nullValue="0")
defined class NullValueSpaceProperty

scala> class SomeClassAgain(@BeanProperty @(NullValueSpaceProperty @beanGetter) val x:Int)
defined class SomeClassAgain

使用类型别名:

scala> type NVSP = NullValueSpaceProperty @beanGetter
defined type alias NVSP

scala> class SomeClassAgain2(@BeanProperty @NVSP val x:Int)defined class SomeClassAgain2

这个解决方案有一个小问题。 在运行时无法保留Scala中定义的注释。 因此,如果您需要在运行时使用注释,则可能需要使用Java进行扩展。 我说, 可能是因为我不知道,如果这种限制已经进行了修正。

这样行吗?

type MyAnnotation[+X] = @BeanProperty
                        @(SpaceProperty @beanGetter)(nullValue = 0) X

val myValue: MyAnnotation[MyType] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM