2012-11-09 123 views
10

在我的代码点多,三个注释一起出现:斯卡拉类型别名注解

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

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

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

我所能做的最好的是:

type ScalaSpaceProperty = SpaceProperty @beanGetter 

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

是否有可能定义一个类型别名,其中的参数被应用到最后一两个注解?

+0

您是否在使用Scala和GigaSpaces?哇! – Madoc

+0

http://edmondo1984.squarespace.com/ – Edmondo1984

回答

4

不可以可以在Scala 2.10中写一个宏来做到这一点,我想(但目前文档不可用,所以我无法检查)。

+6

您无法在2.10.0中为此编写宏。也许这个功能会让它变成2.10.1,但我不确定。 –

3

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

0

这是行不通的?

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

val myValue: MyAnnotation[MyType]