【问题标题】:Scala Type aliases for annotationsScala 类型的注解别名
【发布时间】:2012-11-09 14:42:32
【问题描述】:

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

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

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

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

我能做的最好的事情是:

type ScalaSpaceProperty = SpaceProperty @beanGetter

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

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

【问题讨论】:

标签: java scala annotations


【解决方案1】:

没有。您可以在 Scala 2.10 中编写一个宏来执行此操作,我认为(但文档目前不可用,所以我无法检查)。

【讨论】:

  • 您不能在 2.10.0 中为此编写宏。也许这个功能会进入 2.10.1,但我不确定。
【解决方案2】:

我知道的类型别名注释的唯一例子是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 中进行扩展。我说可能是因为我不确定这个限制是否已经被修改。

【讨论】:

    【解决方案3】:

    这行得通吗?

    type MyAnnotation[+X] = @BeanProperty
                            @(SpaceProperty @beanGetter)(nullValue = 0) X
    
    val myValue: MyAnnotation[MyType] 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 2018-04-21
      相关资源
      最近更新 更多