Scala入门到精通——第十六节 泛型与注解
本节主要内容
- 泛型(Generic Type)简单介绍
- 注解(Annotation)简单介绍
- 注解经常使用场景
1. 泛型(Generic Type)简单介绍
泛型用于指定方法或类能够接受随意类型參数,參数在实际使用时才被确定,泛型能够有效地增强程序的适用性,使用泛型能够使得类或方法具有更强的通用性。泛型的典型应用场景是集合及集合中的方法參数,能够说同java一样,scala中泛型无处不在,详细能够查看scala的api
1 泛型类
//单个泛型參数的使用情况
class Person[T](var name:T)
class Student[T](name:T) extends Person(name)
object GenericDemo {
def main(args: Array[String]): Unit = {
println(new Student[String]("摇摆少年梦").name)
}
}
多个泛型參数的使用情况:
class Person[T](var name:T)
class Student[T,S](name:T,var age:S) extends Person(name)
object GenericDemo {
def main(args: Array[String]): Unit = {
println(new Student[String,Int]("摇摆少年梦",18).name)
}
}
D:\ScalaWorkspace\ScalaChapter16\bin\cn\scala\xtwy>javap -private Person.class
Compiled from "GenericDemo.scala"
public class cn.scala.xtwy.Person<T> {
private T name;
public T name();
public void name_$eq(T);
public cn.scala.xtwy.Person(T);
}
D:\ScalaWorkspace\ScalaChapter16\bin\cn\scala\xtwy>javap -private Student.class
Compiled from "GenericDemo.scala"
public class cn.scala.xtwy.Student<T, S> extends cn.scala.xtwy.Person<T> {
private S age;
public S age();
public void age_$eq(S);
public cn.scala.xtwy.Student(T, S);
}
从上面的代码不难看出,scala泛型对应于java中的泛型,掌握了java中的泛型也就掌握了scala中的泛型
2. 注解(Annotation)简单介绍
Annotation是一种对程序代码进行描写叙述的结构化信息。
Annotation能够分布在程序的不论什么地方,能够注解变量、类、方法、參数等多种元素,它的主要功能有以下几种:
1 自己主动生成scala文档
scala.collection.immutable.HashMap类对应部分源代码:
/** This class implements immutable maps using a hash trie.
*
* '''Note:''' The builder of this hash map may return specialized representations for small maps.
*
* @tparam A the type of the keys contained in this hash map.
* @tparam B the type of the values associated with the keys.
*
* @author Martin Odersky
* @author Tiark Rompf
* @version 2.8
* @since 2.3
* @see [[http://docs.scala-lang.org/overviews/collections/concrete-immutable-collection-classes.html#hash_tries "Scala's Collection Library overview"]]
* section on `Hash Tries` for more information.
* @define Coll `immutable.HashMap`
* @define coll immutable hash map
* @define mayNotTerminateInf
* @define willNotTerminateInf
*/
@SerialVersionUID(2L)
class HashMap[A, +B] extends AbstractMap[A, B]
with Map[A, B]
with MapLike[A, B, HashMap[A, B]]
with Serializable
with CustomParallelizable[(A, B), ParHashMap[A, B]]
{
上述annotation生成的文档内容例如以下:
2 检查程序中可能出现的语法问题
//当程序使用该API时,给出对应提示,属于语法检查范畴
@deprecated("Use the `merged` method instead.", "2.10.0")
def merge[B1 >: B](that: HashMap[A, B1], mergef: MergeFunction[A, B1] = null): HashMap[A, B1] = merge0(that, 0, liftMerger(mergef))
3 规定程序行为
//@BeanProperty。要求程序生成对应getter,setter方法。与java命名规范一致
class Student[T,S](name:T,var age:S) extends Person(name)
{
@BeanProperty var studentNo:String=null
}
当然。annotation还有其他功能,上面三种仅仅是平时在编敲代码时最为经常使用的功能
annotation具有例如以下语法格式:
class A
class B extends A{
//同java一样。採用@+注解关键字对方法、变量
//类等进行注解标识
//以下的注解用于标识getName方法在未来会被丢弃
//不推荐使用
@deprecated def getName()="Class B"
}
object AnnotationDemo{
def main(args: Array[String]): Unit = {
var b=new B()
//在调用的时候。编译器出给出对应提示
b.getName()
}
}
3. 注解经常使用场景
注解的经常使用场景包含volatile。transient。native,SerialVersionUID,serializable5个。用于对变量或方法进行注解,当中volatile用于标识变量可能会被多个线程同一时候改动,它不是线程安全的;transient用于标识变量是瞬时的,它不会被持久化;native用于标识算法来自C或C++代码实现
abstract class A
{
//native用于标记 cplusplusMethod为c或c++中实现的本地方法
@native def cplusplusMethod()
}
//标记B可被序列化
//注解声明序列化版本号
@SerialVersionUID(1000330L)
@serializable
class B extends A{
//volatile注解标记变量name非线程安全
@volatile var name:String="B"
//transient注解用于标记变量age不被序列化
@transient var age:Int=40
}
以下举下对象序列化的样例:
//以下的代码编译时不会出问题,但运行时会抛出异常
class Person{
var name:String="zzh"
var age:Int=0
override def toString()="name="+name+" age="+age
}
object Serialize {
def main(args: Array[String]): Unit = {
val file = new File("person.out")
val oout = new ObjectOutputStream(new FileOutputStream(file))
val person = new Person
oout.writeObject(person)
oout.close()
val oin = new ObjectInputStream(new FileInputStream(file))
val newPerson = oin.readObject()
oin.close();
println(newPerson)
}
}
Exception in thread "main" java.io.NotSerializableException: cn.scala.xtwy.serialize.Person
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at cn.scala.xtwy.serialize.Serialize$.main(Serialize.scala:22)
at cn.scala.xtwy.serialize.Serialize.main(Serialize.scala)
此时在Person类前加@serializable则能够对对象进行正常序列化
//声明对象可序列化
@serializable
class Person{
var name:String="zzh"
var age:Int=0
override def toString()="name="+name+" age="+age
}
object Serialize {
def main(args: Array[String]): Unit = {
val file = new File("person.out")
val oout = new ObjectOutputStream(new FileOutputStream(file))
val person = new Person
oout.writeObject(person)
oout.close()
val oin = new ObjectInputStream(new FileInputStream(file))
val newPerson = oin.readObject()
oin.close();
println(newPerson)
}
}
//反序列化后的输出结果为:
//name=zzh age=0
假设给成员变量加@transient注解的话。则对应的成员变量不会被序列化。此时假设进行反序列化的话,对应成员变量为null,如:
package cn.scala.xtwy.serialize
import java.io.File
import java.io.ObjectOutputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.FileInputStream
@serializable
class Person{
//@transient注解声明后。成员变量不会被充列化
@transient var name:String="zzh"
var age:Int=0
override def toString()="name="+name+" age="+age
}
object Serialize {
def main(args: Array[String]): Unit = {
val file = new File("person.out")
val oout = new ObjectOutputStream(new FileOutputStream(file))
val person = new Person
oout.writeObject(person)
oout.close()
val oin = new ObjectInputStream(new FileInputStream(file))
val newPerson = oin.readObject()
oin.close();
println(newPerson)
}
}
//反序列化后的输出
//name=null age=0
加入公众微信号,能够了解很多其他最新Spark、Scala相关技术资讯
Scala入门到精通——第十六节 泛型与注解的更多相关文章
- Scala入门到精通——第二十四节 高级类型 (三)
作者:摆摆少年梦 视频地址:http://blog.csdn.net/wsscy2004/article/details/38440247 本节主要内容 Type Specialization Man ...
- Scala入门到精通——第十五节 Case Class与模式匹配(二)
本节主要内容 模式匹配的类型 for控制结构中的模式匹配 option类型模式匹配 1. 模式的类型 1 常量模式 object ConstantPattern{ def main(args: Arr ...
- Scala入门到精通——第二十九节 Scala数据库编程
本节主要内容 Scala Mavenproject的创建 Scala JDBC方式訪问MySQL Slick简单介绍 Slick数据库编程实战 SQL与Slick相互转换 本课程在多数内容是在官方教程 ...
- Scala入门到精通——第十九节 隐式转换与隐式參数(二)
作者:摇摆少年梦 配套视频地址:http://www.xuetuwuyou.com/course/12 本节主要内容 隐式參数中的隐式转换 函数中隐式參数使用概要 隐式转换问题梳理 1. 隐式參数中的 ...
- Simulink仿真入门到精通(十六) Simulink基于模型设计的工业应用概述
16.1 Simulink用途概述 在基于模型设计广泛应用于汽车电子嵌入式开发的今天,MBD(Model Besed Design)技术也逐步推广到各种嵌入式控制方面.与传统的嵌入式开发相比,BMD以 ...
- Scala入门到精通
原文出自于: http://my.csdn.net/lovehuangjiaju 感谢! 也感谢,http://m.blog.csdn.net/article/details?id=52233484 ...
- Simulink仿真入门到精通(十九) 总结回顾&自我练习
从2019年12月27到2020年2月12日,学习了Simulink仿真及代码生成技术入门到精通,历时17天. 学习的比较粗糙,有一些地方还没理解透彻,全书梳理总结: Simulink的基础模块已基本 ...
- 第三百八十六节,Django+Xadmin打造上线标准的在线教育平台—HTML母版继承
第三百八十六节,Django+Xadmin打造上线标准的在线教育平台—HTML母版继承 母板-子板-母板继承 母板继承就是访问的页面继承一个母板,将访问页面的内容引入到母板里指定的地方,组合成一个新页 ...
- ASP.NET MVC深入浅出系列(持续更新) ORM系列之Entity FrameWork详解(持续更新) 第十六节:语法总结(3)(C#6.0和C#7.0新语法) 第三节:深度剖析各类数据结构(Array、List、Queue、Stack)及线程安全问题和yeild关键字 各种通讯连接方式 设计模式篇 第十二节: 总结Quartz.Net几种部署模式(IIS、Exe、服务部署【借
ASP.NET MVC深入浅出系列(持续更新) 一. ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态模 ...
随机推荐
- java读取nc文件的问题,前端ajax 发送参数进行交互的实例
1.问题背景: 需要解析nc文件的数据源,获取一个三维数据,并计算器开发值. java 后台处理: 定以一个实例来接收解析的数据并返回给前端. package cn.edu.shou.domain; ...
- 什么是JavaScript框架-------share
摘要:现代网站和web应用程序趋向于依赖客户端的大量的javascript来提供丰富的交互.特别是通过不刷新页面的异步请求来返回数据或从服务器端的脚本(或数据系统)中得到响应.在这篇文章中,你将会了解 ...
- Ubuntu 开机出现 "Your system is running in low-graphics mode"
Ubuntu 开机出现 "Your system is running in low-graphics mode" 可能是权限问题 按网上的方法发现sudo命令无法使用,且系统变为 ...
- spring-mvc junit测试
import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; impor ...
- You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, i
[ERROR] Unknown lifecycle phase "mvn". You must specify a valid lifecycle phase or a goal ...
- Codeforces 5D Follow Traffic Rules
[题意概述] 某个物体要从A途经B到达C,在通过B的时候速度不能超过vd. 它的加速度为a,最大速度为vm:AB之间距离为d,AC之间距离为L: 问物体最少花多少时间到达C. [题解] 分情况讨论. ...
- 关于java.io.FileNotFoundException: /static/count.txt (No such file or directory) 问题的解决
这个是BUG网上有三种合理的解释: 1)这个文件在你的程序中可能涉及了读写操作,但是普通用户没有这个权限,所以加上权限就好 chmod count.txt 2)在Linux文件上下层目录是以斜杠 ' ...
- Apollo配置中心的使用
1. 自己搭建Apollo配置中心 碰到如下错误: nested exception is org.hibernate.HibernateException: Access to DialectRes ...
- hdu3376 Matrix Again
最大费用最大流 咋写?取个相反数就可以了-- #include <iostream> #include <cstring> #include <cstdio> #i ...
- NYOJ 239 月老的难题
月老的难题 时间限制:1000 ms | 内存限制:65535 KB 难度:4 描述 月老准备给n个女孩与n个男孩牵红线,成就一对对美好的姻缘. 现在,由于一些原因,部分男孩与女孩可能结成幸福 ...