01.@BeanProperty


Scala 為了提供能與 Java Bean 約定要求, 對 Field 必要擁有 Getter 與 Setter 方法, 並加有 getXXX / setXXX, Scala 使用顯示的註釋型別(Annotaion)來達到這目的:

@BeanProperty 繼承來自
class BeanProperty extends Annotation with StaticAnnotation

撰寫下式
@BeanProperty var status = ""

你可以得到下列二個等式
def setStatus(s: String) { this.status = s }
def getStatus: String = this.status

留意的一點是, 如果型別為 Boolean, 且你需要獲得的命名為 isXXX, 必須使用 scala.reflect.BooleanBeanProperty 作為替代.

在 constractor 中定義
  • var => get/set
  • val => get
  • [none] => // private, no get/set


Example



無使用 @BeanProperty

scala> class WisdomFish01 {
     | var master = 1
     | }
defined class WisdomFish01

scala> val wf = new WisdomFish01
wf: WisdomFish01 = WisdomFish01@60419710

scala> wf.

asInstanceOf   equals         getClass       hashCode       isInstanceOf   master         master_=       notify
notifyAll      toString       wait


使用 scala.reflect.BeanProperty

scala> import scala.reflect._

scala> class WisdomFish {
     | @BeanProperty var master: String = "Kuo"
     | }
defined class WisdomFish

scala> val wf = new WisdomFish
x: WisdomFish = A@2818de48

scala> wf.

asInstanceOf   equals         getClass       getMaster      hashCode       isInstanceOf   master         master_=
notify         notifyAll      setMaster      toString       wait



@BooleanBeanProperty

scala> class WisdomFish02 {                                                           
     | import scala.reflect._                                                         
     | @BooleanBeanProperty
     | // @scala.reflect.BooleanBeanProperty
     | var master: Boolean = true
     | }
defined class WisdomFish02

scala> val wf2 = new WisdomFish02
wf2: WisdomFish02 = WisdomFish02@58d731c4

scala> wf2.

asInstanceOf   equals         getClass       hashCode       isInstanceOf   isMaster       master         master_=
notify         notifyAll      setMaster      toString       wait


Scala 2.8 


class BooleanBeanProperty extends Annotation with StaticAnnotation

This annotation has the same functionality as scala.reflect.BeanProperty, but the generated Bean getter will be named isFieldName instead ofgetFieldName.



class BeanProperty extends Annotation with StaticAnnotation

When attached to a field, this annotation adds a setter and a getter method following the Java Bean convention. For example:

   @BeanProperty
   var status = ""

adds the following methods to the class:

   def setStatus(s: String) { this.status = s }
   def getStatus: String = this.status
 

For fields of type Boolean, if you need a getter named isStatus, use the scala.reflect.BooleanBeanProperty annotation instead.






覆寫Bean方法

scala> class A {                  
     | import scala.reflect._     
     | @BeanProperty val master = 1
     | def setMaster(a: Int) = master + a
     | }
defined class A





Reference


  • http://daily-scala.blogspot.com/2009/09/beanproperties.html


Comments