Scala 為了提供能與 Java Bean 約定要求, 對 Field 必要擁有 Getter 與 Setter 方法, 並加有 getXXX / setXXX, Scala 使用顯示的註釋型別(Annotaion)來達到這目的: @BeanProperty 繼承來自 撰寫下式 @BeanProperty var status = "" 你可以得到下列二個等式 def setStatus(s: String) { this.status = s } def getStatus: String = this.status 留意的一點是, 如果型別為 Boolean, 且你需要獲得的命名為 isXXX, 必須使用 scala.reflect.BooleanBeanProperty 作為替代. 在 constractor 中定義
Example無使用 @BeanPropertyscala> 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
@BooleanBeanPropertyscala> 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 source: BooleanBeanProperty.scala 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 source: BeanProperty.scala 覆寫Bean方法scala> class A { | import scala.reflect._ | @BeanProperty val master = 1 | def setMaster(a: Int) = master + a | } defined class A |
C06.物件導向設計(OOP) > 0601.類別(Classes) >