Generics and annotations in Java

Posted by surajkandukuri on Sun, 26 Apr 2020 07:02:31 +0200

1, Use of enumeration classes

1. Description of enumeration class:

  1. Understanding of enumeration class: there are only a limited number of objects in the class, which are certain. We call this class an enumeration class

  2. Enumeration classes are strongly recommended when you need to define a set of constants

  3. Implementation of enumeration class:

    Need to customize before JDK 5.0

    enum keyword is added after JDK 5 to define enumeration class

  4. If there is only one object in the enumeration class, it can be used as the implementation of singleton mode.

  5. Properties of enumeration class:

    The properties of enumeration class objects should not be allowed to be changed, so private final should be used to decorate the attributes of enumeration class decorated with private final. If the enumeration class explicitly defines a constructor with parameters, the corresponding incoming parameters must also be listed when enumerating values

2. How to customize enumeration class?

Step:

  1. Privatize the constructor to ensure that its objects cannot be created outside the class;
  2. An example of creating an enumeration class inside a class. Declared as: public static final;
  3. If the object has instance variables, it should be declared as private final and initialized in the constructor;

Code example:

//Custom enumeration class
class Season{
    //1. Declare the properties of the Season object: private final decoration
    private final String seasonName;
    private final String seasonDesc;

    //2. Privatize the constructor of the class and assign a value to the object property
    private Season(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //3. Provide multiple objects of the current enumeration class: public static final
    public static final Season SPRING = new Season("spring","in the warm spring , flowers are coming out with a rush");
    public static final Season SUMMER = new Season("summer","Summer heat");
    public static final Season AUTUMN = new Season("Autumn","fresh autumn weather");
    public static final Season WINTER = new Season("winter","a world of ice and snow");

    //4. Other claims 1: get the properties of enumeration objects
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
    //4. Other claims 1: toString()
    @Override
    public String toString() {
        return "Season{" +
            "seasonName='" + seasonName + '\'' +
            ", seasonDesc='" + seasonDesc + '\'' +
            '}';
    }
}

3. Add enum to define enumeration class in JDK 5.0.

instructions:

  • Enum class defined by enum inherits java.lang.Enum class by default, so other classes can no longer be inherited

  • Constructors of enumeration classes can only use the private permission modifier

  • All instances of an enumeration class must be explicitly listed in the enumeration class ("," delimited ";" end). The listed instance system will automatically add public static final decoration

  • Enum class objects must be declared on the first line of an enum class

Code example:

//Enumerating classes using the enum keyword
enum Season1 {
    //1. Provide the object of the current enumeration class, separate multiple objects with "," and end with ";"
    SPRING("spring","in the warm spring , flowers are coming out with a rush"),
    SUMMER("summer","Summer heat"),
    AUTUMN("Autumn","fresh autumn weather"),
    WINTER("winter","a world of ice and snow");

    //2. declare the attribute of Season object: private final
    private final String seasonName;
    private final String seasonDesc;

    //2. Privatize the constructor of the class and assign a value to the object property

    private Season1(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4. Other claims 1: get the properties of enumeration objects
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }

}

Common methods of Enum class:

  1. values() method: returns an array of objects of enumeration type. This method can easily traverse all enumeration values.

  2. valueOf(String str): you can convert a string into a corresponding enumeration class object. It is required that the string must be the "name" of the enumeration class object. If not, there will be a runtime exception IllegalArgumentException

  3. toString(): returns the name of the current enumeration class object constant

Code example:

Season1 summer = Season1.SUMMER;
//toString(): returns the name of an enumeration class object
System.out.println(summer.toString());

//        System.out.println(Season1.class.getSuperclass());
System.out.println("****************");
//values(): returns an array of enumeration class objects
Season1[] values = Season1.values();
for(int i = 0;i < values.length;i++){
    System.out.println(values[i]);
}
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): returns the object in the enumeration class whose object name is objName.
Season1 winter = Season1.valueOf("WINTER");
//If there is no enumeration class object of objName, throw an exception: IllegalArgumentException
//        Season1 winter = Season1.valueOf("WINTER1");
System.out.println(winter);

The Enum class objects defined by Enum class are used to implement interfaces respectively:

instructions:

  1. Like normal Java classes, enumeration classes can implement one or more interfaces
  2. If each enumeration value behaves the same way in the interface method that is called to implement, it is only necessary to implement the method uniformly.
  3. If you need each enumeration value to behave differently in the interface method that you call to implement, you can make each enumeration value implement the method separately

Code example:

interface Info{
    void show();
}

//Enumerating classes using the enum keyword
enum Season1 implements Info{
    //1. Provide the object of the current enumeration class, separate multiple objects with "," and end with ";"
    SPRING("spring","in the warm spring , flowers are coming out with a rush"){
        @Override
        public void show() {
            System.out.println("Where is spring?");
        }
    },
    SUMMER("summer","Summer heat"){
        @Override
        public void show() {
            System.out.println("Ningxia");
        }
    },
    AUTUMN("Autumn","fresh autumn weather"){
        @Override
        public void show() {
            System.out.println("Don't come back in autumn");
        }
    },
    WINTER("winter","a world of ice and snow"){
        @Override
        public void show() {
            System.out.println("About in winter");
        }
    };
}

2, Use of annotations

1. Understanding of notes

① New features of jdk 5.0

② Annotation is actually a special tag in the code. These tags can be read during compilation, class loading, runtime, and corresponding processing. By using annotation, the programmer can embed some supplementary information in the source file without changing the original logic.

③ Annotation can be used like a modifier to decorate the declaration of package, class, constructor, method, member variable, parameter and local variable. This information is saved in the "name = value" pair of annotation.

④ In Java se, annotations are used for simple purposes, such as marking outdated functions, ignoring warnings, etc. Annotations play a more important role in JavaEE/Android, such as configuring any aspect of the application, replacing the cumbersome code and XML configuration left in the old version of JavaEE.

⑤ Framework = annotation + reflection mechanism + design pattern

2. Use examples of notes

Use Annotation before it @Symbols , and use the Annotation as a modifier. Used to decorate the program elements it supports

Example 1: generate document related annotations

@The author indicates the author who developed this type of module, which is used by multiple authors. Split @ version indicates the version of this type of module @ see reference direction, that is, the description of a parameter in the method by @ param added from the related topic @ since. If there is no parameter, the description of the return value of the method by @ return cannot be written. If the return value type of the method is void, the description of the return value of the method by @ return cannot be written @Exception describes the exceptions that a method may throw. If a method does not throw an exception explicitly with throws, the @ param @return and @ exception tags cannot be written, which are only used for the method. @Format requirements for param: @ param parameter name parameter type parameter description @ return format requirements: @ return return return value type return value description @ exception format requirements: @ exception exception type exception description @ param and @ exception can be in parallel

Code example:

/**
 * @author bruce
 * @project_name JavaSenior
 * @package_name com.bruce.java
 * @create 2020-04-26 10:58
 */
public class AnnotationTest {
    /**
     *Main method of program
     * @param args Incoming command line parameters
     */
    public static void main(String[] args) {

    }

    /**
     * Find circular area
     * @param radius Radius of area
     * @return Area value
     */
    public static double getArea(double radius){
        return Math.PI * radius * radius;
    }
}

Example 2: format checking at compile time (basic notes built into JDK)

@Override: qualifies overriding the parent method, which can only be used for the method @ Deprecated: to indicate that the decorated element (class, method, etc.) is obsolete. Usually because the decorated structure is dangerous or there is a better choice @ SuppressWarnings: suppress compiler warnings

Code example:

public class AnnotationTest{
    public static void mian (String [] args){
        @SuppressWarning("unused")
        int a = 0;
    }
    @Deprecated
    public void print(){
        System.out.print("Outdated approach");
    }
    @Override
    public String toString(){
        return "Rewritten toString Method";
    }
}

Example 3: tracking code dependency and realizing the function of replacing configuration file

Annotation driven development is widely used when using Spring framework.

3. How to define annotation

Refer to @ SuppressWarnings definition

  1. The annotation declaration is: @ interface
  2. Internally defined members, usually represented by value
  3. You can specify the default value of a member, defined with default
  4. If the custom annotation has no members, it indicates that it is an identification function.

explain:

  • If the annotation has members, you need to indicate the value of the member when using the annotation.
  • A custom annotation must be accompanied by an annotation's information processing flow (using reflection) to make sense.
  • Two meta annotations will be indicated when the user-defined annotation passes: Retention and Target

Code example:

@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";
}

4. Meta notes:

An annotation that explains an existing annotation.

There are four meta annotations provided by JDK 5.0:

  1. Retention: Specifies the life cycle of the decorated Annotation: SOURCE\CLASS (default behavior) - RUNTIME can only be obtained by reflection if the Annotation is declared as a RUNTIME life cycle.
  2. Target: used to specify which program elements can be decorated by the decorated Annotation
  3. Documented: indicates that the modified annotation is preserved when it is parsed by javadoc.
  4. Inherited: annotations decorated by it will be inherited.

Analogy: metadata concept: String name = "Tom"; modification of existing data

5. How to obtain annotation information:

Get and call by launching.

Premise: the lifecycle state declared in the meta annotation Retention of this annotation is required to be: RUNTIME

6. New features annotated in JDK 8.0:

Repeatable notes, type notes

6.1 repeatable notes:

① Declare @ Repeatable on myannotations with member value MyAnnotations.class

② MyAnnotations have the same Target and Retention meta annotations as MyAnnotations.

6.2 type notes:

Elementtype.type'parameter indicates that the annotation can be written in the declaration statement of type variable (such as generic declaration)

Elementtype.type'use indicates that the annotation can be written in any statement that uses a type.

Topics: Programming Spring JDK Java JavaEE