一、Bean属性
### --- Bean属性概述
~~~ JavaBean规范把Java属性定义为一堆getter和setter方法。
~~~ 类似于Java,当将Scala字段标注为 @BeanProperty时,getFoo和setFoo方法会自动生成。
~~~ 使用@BeanProperty并不会影响Scala自己自动生成的getter和setter方法。
### --- 在使用时需要导入包scala.beans.BeanProperty
import scala.beans.BeanProperty
class Teacher {
@BeanProperty var name:String = _
}
object BeanDemo{
def main(args: Array[String]): Unit = {
val tea: Teacher = new Teacher
tea.name = "zhagnsan"
tea.setName("lisi") //BeanProperty生成的setName方法
println(tea.getName) //BeanProperty生成的getName方法
}
}
### --- 上述Teacher类中共生成了四个方法:
1. name: String
2. name_= (newValue: String): Unit
3. getName(): String
4. setName (newValue: String): Unit
二、编程实现
### --- 编程实现
package yanqi.cn.part04
//需要导入下面的包
import scala.beans.BeanProperty
class Teacher {
@BeanProperty
var name: String = _
}
object BeanDemo {
def main(args: Array[String]): Unit = {
val teacher=new Teacher
teacher.name="jacky"
teacher.name_=("tom")
println(teacher.name)
//BeanProperty生成的setName方法
teacher.setName("lisi")
//BeanProperty生成的getName方法
println(teacher.getName)
}
}
### --- 编译打印
D:\JAVA\jdk1.8.0_231\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=55551:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath D:\JAVA\jdk1.8.0_231\jre\lib\charsets.jar;D:\JAVA\jdk1.8.0_231\jre\lib\deploy.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\access-bridge-64.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\cldrdata.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\dnsns.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\jaccess.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\jfxrt.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\localedata.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\nashorn.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\sunec.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\sunjce_provider.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\sunmscapi.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\sunpkcs11.jar;D:\JAVA\jdk1.8.0_231\jre\lib\ext\zipfs.jar;D:\JAVA\jdk1.8.0_231\jre\lib\javaws.jar;D:\JAVA\jdk1.8.0_231\jre\lib\jce.jar;D:\JAVA\jdk1.8.0_231\jre\lib\jfr.jar;D:\JAVA\jdk1.8.0_231\jre\lib\jfxswt.jar;D:\JAVA\jdk1.8.0_231\jre\lib\jsse.jar;D:\JAVA\jdk1.8.0_231\jre\lib\management-agent.jar;D:\JAVA\jdk1.8.0_231\jre\lib\plugin.jar;D:\JAVA\jdk1.8.0_231\jre\lib\resources.jar;D:\JAVA\jdk1.8.0_231\jre\lib\rt.jar;E:\NO.Z.10000——javaproject\NO.Z.00002.Hadoop\ScalaPro\out\production\ScalaPro;D:\JAVA\scala-2.12.2\lib\scala-library.jar;D:\JAVA\scala-2.12.2\lib\scala-reflect.jar yanqi.cn.part04.BeanDemo
tom
lisi
Process finished with exit code 0