2012-11-09 109 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]