11、枚举与注解:
枚举(Enumeration):
Season的例子:
package com.jiangxian.enum_;
public class Enumeration01 {
public static void main(String[] args) {
Season spring = new Season("Spring", "warm");
Season summer = new Season("Summer", "hot");
Season autumn = new Season("Autumn", "cool");
Season winter = new Season("Winter", "cold");
// 对于季节而言,其对象(具体值),是固定的四个,不会有更多
// 所以我们这种设计思路是有问题的
// 这种传统的方法是不可以的 ====> 所以出现了 枚举类[枚:一个个,举:列举;即把具体的对象一个个列举出来的类]
Season computer = new Season("Computer", "hard");
}
}
class Season{
private String name;
private String description;
public Season(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
在这个例子中,我们发现了一些特点:
- 值是有限的几个值(spring,summer,autumn,winter);
- 只读,不需要修改。
枚举的介绍:
- 枚举——enumeration;
- 枚举是一组常量的集合;
- 可以这样理解:枚举是一种特殊的类,里面只包含一组有限的特定的对象
自定义枚举类:
- 不需要提供 setXxx 方法,因为枚举对象值通常为只读;
- 对枚举对象/属性使用 final + static 共同修饰,实现底层优化;
- 枚举对象名通常使用全部大写,常量的命名规范;
- 枚举对象根据需要,可以有多个属性。
package com.jiangxian.enum_;
/**
* @author JiangXian~
* @version 1.0
*/
public class Enumeration02 {
public static void main(String[] args) {
System.out.println(Season.SPRING);
System.out.println(Season.SUMMER);
System.out.println(Season.AUTUMN);
System.out.println(Season.WINTER);
}
}
// 演示自定义枚举的实现
class Season{
private String name;
private String description;
public final static Season SPRING = new Season("Spring", "warm");
public final static Season SUMMER = new Season("Summer", "hot");
public final static Season AUTUMN = new Season("Autumn", "cool");
public final static Season WINTER = new Season("Winter", "cold");
// 1.先把构造器做成私有的形式,防止直接被 new
// 2.删除 setXxx 方法,保证只读;
// 3.在Season内部,创建规定的对象
// 4.使用静态属性会导致Season的加载,优化可以使用final
private Season(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
小结特点:
- 构造器私有化;
- 本类内部创建一些对象;
- 对外暴露对象(public final static);
- 可以提供get方法,但是不能有set。
使用enum关键字实现枚举:
- enum 关键字代替 class;
- 需要定义的常量写在最前面,格式:常量名(参数列表);
- 多个常量间用逗号隔开。
/**
* @author JiangXian~
* @version 1.0
*/
public class Enumeration03 {
public static void main(String[] args) {
System.out.println(Season2.SPRING);
System.out.println(Season2.SUMMER);
System.out.println(Season2.AUTUMN);
System.out.println(Season2.WINTER);
}
}
// 使用enum关键字生成枚举类
enum Season2{
// 解读:常量名(实参列表);
// 多个常量用逗号间隔
// 同时要使用enum实现的话,要将需要定义的常量放在最前面。
SPRING("Spring","warm"),
SUMMER("Summer","hot"),
AUTUMN("Autumn","cool"),
WINTER("Winter","cold");
private String name;
private String description;
private Season2(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
注意事项:
- 当我们使用 enum 关键字开发一个枚举类的时候,其会默认继承Enum类,而且是一个final类型;
- 传统的 public final static Season2 SPRING = new Season2(“Spring”,“warm”);简化成了SPRING(“Spring”,“warm”);
- 若使用无参构造器 创建 枚举类的对象的化,则实参列表和小括号都可以省略——SPRING即可;
- 当有多个枚举对象时,使用 , 间隔,最后又个 ; 收尾;
- 枚举对象必须放在枚举类的首行。
enum常用方法:
toString():
Enum类重写了toString方法,返回的是当前对象名,子类可以再重写(enum 关键字创建的类自动继承Enum),用于返回对象的属性。
name():
返回当前对象名(常量名),子类中不能重写。
ordinal():
返回当前对象的位置号,默认从零开始(可以理解为,常量会按照定义的顺序被存储在一个数组中)。
values():
返回当前枚举类的所有常量,返回的类型是一个 类型数组。
valueOf():
将字符串转化为枚举对象,要求字符串必须是已有的常量名,否则会报错。
compareTo():
比较两个枚举对象的位置号,若为0表示相等,若为正数表示调用对象在比较对象的后面,若为负数则在前面。
/**
* @author JiangXian~
* @version 1.0
*/
public class Enumeration03 {
public static void main(String[] args) {
System.out.println(Season2.SPRING);
System.out.println(Season2.SUMMER);
System.out.println(Season2.AUTUMN);
System.out.println(Season2.WINTER);
System.out.println(Season2.SUMMER.name());
System.out.println(Season2.SUMMER.ordinal());
Season2[] values = Season2.values();
System.out.println("==========Season==========");
// 增强for循环,用于遍历容器
for(Season2 season:values){
System.out.println(season);
}
Season2 season2 = Season2.valueOf("SUMMER");
// Season2 season21 = Season2.valueOf("S");
System.out.println(Season2.SUMMER.compareTo(Season2.WINTER));
System.out.println(Season2.SUMMER.compareTo(Season2.SPRING));
}
}
// 使用enum关键字生成枚举类
enum Season2{
// 解读:常量名(实参列表);
// 多个常量用逗号间隔
// 同时要使用enum实现的话,要将需要定义的常量放在最前面。
SPRING("Spring","warm"),
SUMMER("Summer","hot"),
AUTUMN("Autumn","cool"),
WINTER("Winter","cold");
private String name;
private String description;
private Season2(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
}
使用细节:
- 使用 enum 关键字后,就不能再继承其它类了(因为使用enum会自动继承Enum类,而Java是单继承机制);
- 和普通类一样,枚举类也可以实现接口。
- enum 类 implements 接口1,接口…{}
注解(Annotation):
注解的理解:
- 注解也被称为元数据(Metadata),用于修饰 包、类、方法、属性、构造器、局部变量等信息;
- 和注释一样,注解不影响程序逻辑,但注解可以被编译或运行,相当于嵌入再程序中的补充信息;
- 在JavaSE中,注解的使用目的比较简单,例如标记过时的功能,忽略警告等。在JavaEE中,注解占据了更重要的角色,例如用来配置应用程序的任何切面,代替JavaEE旧版中所遗留的冗余代码和XML配置等。
Annotation基本介绍:
使用 Annotation 时要在前面增加 @ 符号,并把该 Annotation 当作一个修饰符使用。用于修饰它支持的程序元素。
三个基本的 Annotation:
- @Override:限定某个方法,是重写父类方法,该注解只能用于方法;
- @Deprecated:用于表示某个程序元素已经过时;
- @SuppressWarnings:抑制编译器警告。
@Override:
限定某个方法,是重写父类方法,该注解只能用于方法。
@Override
public String toString() {
return "Season{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
解释:
- 此时@Override放在toString方法上,表示子类的toString方法重写了父类的toString方法;
- 若这边没有写@Override,而父类仍然有该方法,还是会重写父类的方法;
- 若写了@Override,则编译器会去检查该方法是否真的重写了父类的方法,若构成重写,则编译通过,否则编译不通过。
- 该注解只能修饰方法,不能修饰其它类,包,属性等(看源码@Target那行)。
@Override的源码:
package java.lang;
import java.lang.annotation.*;
/**
* Indicates that a method declaration is intended to override a
* method declaration in a supertype. If a method is annotated with
* this annotation type compilers are required to generate an error
* message unless at least one of the following conditions hold:
*
* <ul><li>
* The method does override or implement a method declared in a
* supertype.
* </li><li>
* The method has a signature that is override-equivalent to that of
* any public method declared in {@linkplain Object}.
* </li></ul>
*
* @author Peter von der Ahé
* @author Joshua Bloch
* @jls 9.6.1.4 @Override
* @since 1.5
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override { // @interface 不是 interface接口的意思,而是表面这是个注解类
}
@Deprecated:
说明:
- 用于表示某个程序元素已经过时(什么意思呢?就是可以用,但是不建议的意思)。
- 可以修饰方法,类,字段,包,参数等等;
- 其作用主要是做到新旧版本之间的兼容。
- 使用被其注解的元素时,会有一个删除线出现==
像这样~==
@SuppressWarnings:
语法:@SuppressWarnings(“”)
在(“”)中应该写入希望抑制(不显示)警告信息。
有很多的类型,但实际上没必要背,看下黄色的warning信息是什么再一个个的修改,或者就直接all也行。
元注解(了解即可):
基本介绍:
元Annotation用于修饰其它的Annotation,其本身的作用不大,但是看源码的时候需要能看得懂是什么意思。
种类:
- Retention:指定注解的作用范围,三种——SOURCE(源码),CLASS(类),RUNTIME(运行);
- Target:指定注解在哪里使用;
- Documented:指定注解是否会在javadoc中体现;
- Inherited:子类会继承父类注解。
@Retention:
只能修饰一个Annotation定义,用于指定该注解可以保留多长时间,其包含一个RetentionPolicy类型的成员变量,使用@Retention是必须为该value成员变量指定值。
三种值:
- RetentionPolicy.SOURCE:编译器使用后,直接丢弃这种策略的注解
- RetentionPolicy.CLASS:编译器将注解记录在class文件中,当运行java程序时,JVM不会保留注解。这是默认值。
- RetentionPolicy.RUNTIME:编译器将注解记录在class文件中,当运行java程序时,JVM会保留注解。程序可以通过反射获取该注解。
看一下@Override的源码,其是SOURCE的值:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE) // 在编译的时候生效,其余部分就没有用了
public @interface Override {
}
@Target:
用于修饰 Annotation 定义,用来指定被修饰的 Annotation 能用于修饰哪些程序元素。@Target 也包含一个名为 value 的成员变量。
看一下@Deprecated 源码:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}
@Documented:
用于指定该元 Annotation 修饰的 Annotation 类将被 javadoc 工具提取成文档,即在生成文档时,可以看到该注解。
定义为Documented的注解必须将Retention的值设置为RUNTIME。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}
@Inherited:
被它修饰的 Annotation 将具有继承性,即某个类使用了被 @Inherited 修饰的 Annotation,其子类自动具有该注解。
实际应用中较少,了解即可。