scala教程:@BeanPropetry注解和setter、getter方法

介绍

由于很多 Java 框架都利用反射调用 getXXX 和 setXXX 方
法

scala为了和这些框架兼容,也会为 Scala 的属性增加 getXXX 和 setXXX 方法

但不需要手动添加,而是通过 @BeanProperty 注解实现

@BeanProperty

在属性上增加 @BeanPropetry注解,可以自动生成 setXxx() 和 getXxx() 方法

例子

object StdClass {

  def main(args: Array[String]): Unit = {
    val phone:Phone = new Phone()
    println(phone.getCpu())
    println(phone.getName())

class Phone{
  @BeanProperty
  val name:String="iphone15"
  @BeanProperty
  var cpu:String = "A100"

}

反编译 Phone 类

发现新增加了下面方法:

   public String getCpu() {
      return this.cpu();
   }

   public String getName() {
      return this.name();
   }

boolean 类型也生成 getter 方法

java中,成员变量是 boolean 类型,生成的是 isXxx() 方法

scala中,是生成 getXxx() 方法,如下图:

val 成员常量

val 成员常量,由 @BeanProperty 修饰,但是,由于是 val 常量,所以只有 getter,没有 setter


原文出处:/show_1IX1CYjrmO8Y.html