Enum class and notes

First, the use of enumeration class

1. understanding enumeration class: object class is only a finite number, determined. We call such an enumeration type
2. When you need to define a set of constants, it is strongly recommended to use enum class
3. If the enumeration class implementation is only one object can be used as a singleton pattern.

Second, how to define enumeration class

Method 1: Before jdk5.0, custom enumeration class

public class SeasonTest {
    public static void main(String[] args) {
        Season spring = Season.SPRING;
        System.out.println(spring);
    }
}
//自定义枚举类
class Season{
    //1.声明Season对象的属性:private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //2.私有化类的构造器,并给对象属性赋值
    private Season(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //3.提供当前枚举类的多个对象:public static final的
    public static final Season SPRING = new Season("春天","春暖花开");
    public static final Season SUMMER = new Season("夏天","夏日炎炎");
    public static final Season AUTUMN = new Season("秋天","秋高气爽");
    public static final Season WINTER = new Season("冬天","冰天雪地");

    //4.其他诉求1:获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
    //4.其他诉求1:提供toString()
    @Override
    public String toString() {
        return "Season{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}

Second way: jdk5.0, you can use enum keyword to define enumeration class

public class SeasonTest1 {
    public static void main(String[] args) {
        Season1 summer = Season1.SUMMER;
        //toString():返回枚举类对象的名称
        System.out.println(summer.toString());
//        System.out.println(Season1.class.getSuperclass());
        System.out.println("****************");
        //values():返回所有的枚举类对象构成的数组
        Season1[] values = Season1.values();
        for(int i = 0;i < values.length;i++){
            System.out.println(values[i]);
            values[i].show();
        }
        System.out.println("****************");
        Thread.State[] values1 = Thread.State.values();
        for (int i = 0; i < values1.length; i++) {
            System.out.println(values1[i]);
        }
        //valueOf(String objName):返回枚举类中对象名是objName的对象。
        Season1 winter = Season1.valueOf("WINTER");
        //如果没有objName的枚举类对象,则抛异常:IllegalArgumentException
//        Season1 winter = Season1.valueOf("WINTER1");
        System.out.println(winter);
        winter.show();
    }
}

interface Info{
    void show();
}

//使用enum关键字枚举类
enum Season1 implements Info{
    //1.提供当前枚举类的对象,多个对象之间用","隔开,末尾对象";"结束
    SPRING("春天","春暖花开"){
        @Override
        public void show() {
            System.out.println("春天在哪里?");
        }
    },
    SUMMER("夏天","夏日炎炎"){
        @Override
        public void show() {
            System.out.println("宁夏");
        }
    },
    AUTUMN("秋天","秋高气爽"){
        @Override
        public void show() {
            System.out.println("秋天不回来");
        }
    },
    WINTER("冬天","冰天雪地"){
        @Override
        public void show() {
            System.out.println("大约在冬季");
        }
    };

    //2.声明Season对象的属性:private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //2.私有化类的构造器,并给对象属性赋值
    private Season1(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4.其他诉求1:获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
//    //4.其他诉求1:提供toString()
//
//    @Override
//    public String toString() {
//        return "Season1{" +
//                "seasonName='" + seasonName + '\'' +
//                ", seasonDesc='" + seasonDesc + '\'' +
//                '}';
//    }

//    @Override
//    public void show() {
//        System.out.println("这是一个季节");
//    }
}

Three, Enum class common methods:

values () Method: Returns an array of enumerated type. This method can easily traverse all the enumeration values.
valueOf (String str): a character string can be converted into the corresponding enumeration class object. Requirements must be a string enumeration class object "name." If it is not abnormal, there will be runtime: IllegalArgumentException.
toString (): Returns the name of the current class object enumeration constants

Fourth, the use enum keyword defines an enumeration class that implements the interface case

Case 1: implement an interface, implements the abstract method in enum class
Case 2: Let the object enumeration class abstract methods interface were achieved

Fifth, use annotations

1. Understand Annotation:

① jdk 5.0 new features
② Annotation is actually a code of special markers that can be compiled, class loading, be read runtime and executes the corresponding processing. By using the Annotation,
programmers, some additional information embedded in the source file without changing the original logic.
③ In JavaSE using relatively simple annotation purposes, e.g. outdated feature tag, ignore warnings. In JavaEE / Android
annotations occupy a more important role, for example, any cut to configure the application, instead of the old version JavaEE burdensome legacy
code and XML configuration.

2. Annocation uses examples

Example 1: generating a document annotations associated
Example Two: Check format (JDK built three basic annotation) at compile time
@Override: defining override the parent class method, the method can only be used annotation
@Deprecated: for indicating the modified elements (classes, methods etc.) obsolete. Usually because of the risk or presence of the modified structure better alternative
@SuppressWarnings: inhibition compiler warning
Example Three: tracking code dependencies, alternative implementations profile feature

3. How to customize the annotation: reference to the definition of @SuppressWarnings

Notes ① declared: @interface
② internal definition of members, usually value represents
③ can specify default values for members, use default definitions
④ If the custom annotation has no members, indicating a role identity.
If there are members of the comment, when using annotations, you need to specify the value of the member.
Custom annotations must be accompanied by an information processing flow annotation (using reflection) makes sense.
Custom annotation specifies two yuan notes by city: Retention, Target

4 kinds of metadata annotations provided 4. jdk

Yuan Note: existing notes be an explanation notes
Retention: Specifies the modified Annotation life cycle: SOURCE \ CLASS (default behavior) \ RUNTIME
only declared to comment RUNTIME life cycle, in order to get through reflection.
Target: Annotation for specifying a modified program elements which can be used to modify the
low frequency of occurrence
Documented: represents the modified annotation when parsed javadoc, retained.
Inherited: is it modified Annotation will have inherited.

The annotation information acquired by reflecting - to explain the contents of the system when the reflected

6. jdk 8 annotations new features: repeat annotations, annotation type

6.1 can be repeated comment:

① statement @Repeatable on MyAnnotation, members of the value MyAnnotations.class
② MyAnnotation such as the Target and Retention meta-annotation and MyAnnotations same.

6.2 type annotations:

ElementType.TYPE_PARAMETER indicates that the notes can be written on the declaration type variables (such as: generic declaration).
ElementType.TYPE_USE indicates that the notes can be written in any type of use statement.

public class AnnotationTest {
    public static void main(String[] args) {
        Person p = new Student();
        p.walk();
        Date date = new Date(2020, 10, 11);
        System.out.println(date);
        @SuppressWarnings("unused")
        int num = 10;
//        System.out.println(num);
        @SuppressWarnings({ "unused", "rawtypes" })
        ArrayList list = new ArrayList();
    }

    @Test
    public void testGetAnnotation(){
        Class clazz = Student.class;
        Annotation[] annotations = clazz.getAnnotations();
        for(int i = 0;i < annotations.length;i++){
            System.out.println(annotations[i]);
        }
    }
}

//jdk 8之前的写法:
//@MyAnnotations({@MyAnnotation(value="hi"),@MyAnnotation(value="hi")})
@MyAnnotation(value="hi")
@MyAnnotation(value="abc")
class Person{
    private String name;
    private int age;

    public Person() {
    }
    @MyAnnotation
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @MyAnnotation
    public void walk(){
        System.out.println("人走路");
    }
    public void eat(){
        System.out.println("人吃饭");
    }
}

interface Info{
    void show();
}

class Student extends Person implements Info{
    @Override
    public void walk() {
        System.out.println("学生走路");
    }
    public void show() {
    }
}

class Generic<@MyAnnotation T>{
    public void show() throws @MyAnnotation RuntimeException{
        ArrayList<@MyAnnotation String> list = new ArrayList<>();
        int num = (@MyAnnotation int) 10L;
    }
}
@Inherited
@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {

    String value() default "hello";
}
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotations {

    MyAnnotation[] value();
}
Published 25 original articles · won praise 0 · Views 593

Guess you like

Origin blog.csdn.net/CGB1804Great/article/details/104475191