Fundamentals of Java (23) -- Stream stream, enumeration, annotation, custom annotation, meta annotation
1, Stream stream
1. Concept
Stream: it is an interface. Its function is similar to that of pipeline. It is mainly used to filter data. A stream is similar to a collection, but a collection holds data, while a stream holds operations on collection or array data.
Function: use Stream to filter data and simplify Java code.
characteristic:
- Stream itself does not store elements.
- Stream does not change the source object. Instead, they return a new stream that holds the result.
- The Stream operation is delayed and will not be executed until the result is required.
Stream, which provides two types of methods: delay method and termination method.
Deferred method: indicates whether to return the value after calling the Stream method or the Stream object. You can continue to use the Stream method.
Termination method:: indicates that the return value after calling the Stream method is not a Stream object, and the Stream method can no longer be used.
2. Case 1
Understand through cases:
3. Way to get Stream
Collection and its subclasses can create Stream streams. The Map collection does not work.
4. Stream method
5. Case 2
Use cases to understand usage. Here are the requirements:
Implementation code:
2, Enumeration
1. Concept
Concept: when used to represent some fixed values, enumeration can be used to define them. Some enumeration items will be defined in the enumeration class, and the range of values can only be enumeration items.
Format:
Access modifier enum The name of the enumeration { Enumeration item }
2. Enumerate points for attention
- Each enumeration class is a subclass of Enum.
- Each enumeration item is a class.
- Each enumeration item is separated by commas and terminated by semicolons (semicolons can be omitted at the end, which is recommended).
- Get the enumeration item directly through the enumeration class. The enumeration item can be obtained.
- Member variables can be defined in enumeration classes.
- A constructor can exist in an enumeration item, but the constructor must be private and private by default.
- Abstract methods can exist in enumeration classes, and each enumeration item must implement this abstract method.
Enumeration is generally used with switch
3. Practice
4. Enumerate common methods
3, Annotation
1. Explain
Note: used to explain the code for programmers to view.
Annotation: used to explain the code and identify it to the JVM (computer).
2. Definition
Annotation: also known as metadata. A code level description. It is a feature introduced in JDK 1.5 and later versions,
It is at the same level as class, interface and enumeration. It can be declared before packages, classes, fields, methods, local variables, method parameters, etc
Faces are used to describe and annotate these elements.
3. Action classification
Document writing: generate document doc document through the metadata identified in the code.
Code analysis: analyze the code through the metadata identified in the code [use reflection].
Compilation check: enable the compiler to implement basic compilation check [Override] through the metadata identified in the code.
4. Annotations provided by jdk
1.@Override: used to check whether it is a method that overrides the parent class.
2.@Deprecated: used to label methods that are outdated. Outdated methods can be used but are not recommended.
3.@SuppressWarnings: suppress the yellow line warning. value = "all" suppress all yellow line warnings. Annotations can be defined on classes, methods, or attributes.
a. @ Override -- check whether it is a method that overrides the parent class
First define an abstract class, and then define abstract methods inside:
Then look at its subclasses:
You can see the previous comments.
If you change the method name:
The annotation is redlined.
b. @ Deprecated -- Annotation obsolete method
Outdated methods can be used, but are not recommended:
Define an outdated method first:
Then look at the call:
As you can see, draw a horizontal line when calling. But you can still call:
c. @ SuppressWarnings - suppress the yellow line.
If value = "true" is filled in, all yellow lines will be suppressed:
Look at the far right, there are many yellow lines. Then press the yellow line to see:
Now, there is none.
4, Custom annotation
1. Related concepts before use
1.Format composition: A.Meta annotation B.public @interface Deprecated {} 2.Annotation essence:It's an interface(The following line is obtained by decompiling) public interface MyAnno extends java.lang.annotation.Annotation {} 3.Members in interface:(Focus only) Abstract method ==>attribute 4.The return value type of the property must have a return value, and the return value type is limited. The return value cannot be void) A.There are four types and eight basic data types B.String String type C.Enumeration type D.annotation type E.Array types of the above types 5.Syntax for using annotations: @The name of the annotation 6.Attention: A.For the annotation used, all attributes of the annotation must be assigned values, and the attributes are used default The default value can be set without assignment. B.When using annotations to assign a value to an array of attributes, if there is only one value, its braces can be omitted. C.If there is only one attribute of the annotation value Property. When using annotations for assignment, the name of the annotation can be omitted.
2. Practice customizing annotations
It can be seen that custom annotations can create many abstract methods (properties), so here we try to write a custom annotation:
Write a note, blank:
Then define an annotation that creates different types of attributes:
Then write a class and annotate it:
Because the annotation must have a return value, the return value must be filled in:
If you fill in the default value, you can no longer assign a value in the annotation:
As you can see, this is a simple custom annotation.
5, Meta annotation
1. Meta annotation related knowledge
1.Meta annotation:The annotations used to describe annotations are meta annotations. 2.Four meta annotations @Target: It is mainly used to indicate the position of annotation TYPE-Scope on class FIELD-Scope on property METHOD-Scope on method @Retention: It is mainly used for whether annotations can be recognized RetentionPolicy.RUNTIMEļ¼The program generates Class Bytecode file, definition annotation will be jvm To identify. @Documented: Used to mark whether or not api Show this annotation on the document. @Inherited: Used to indicate whether annotations continue to be inherited by subclasses.
2. Case 1 - using annotation and reflection to call any method of a class
Define annotation first:
You can see that although this is a user-defined annotation, there are meta annotations on the user-defined annotation.
Define a class with a method:
Then comes the main code:
@an1(className = "com.qf.cmf.An_lx3.Student",methodName = "method1") // Fill in the package name and class name in the annotation, and then fill in the method name in the annotation public class Demo1 { public static void main(String[] args) { Class demo1class = Demo1.class; // Gets the class of the current class an1 an = (an1) demo1class.getAnnotation(an1.class); // Get the annotation of the current class an.className(); // Take out the value (class name) in the annotation an.methodName(); // Fetch the value (method name) in the annotation Class cls = Class.forName(an.className()); // Get the Student class through the value reflection in the annotation Constructor con = cls.getConstructor(); // Get construction method by reflection Object obj = con.newInstance(); // instantiation Method mt = cls.getMethod("method1"); // Extract method through class mt.invoke(obj); // And then call this method. } }
3. Case 2 - implementing a test tool class with annotations
analysis:
Let's look at this note first:
Next, look at this tool class:
Finally, let's look at the main codes:
public class Demo1 { public static void main(String[] args) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter("error.txt")); // Prepare for subsequent write exceptions to the file int count = 0; // Cumulative number of exceptions TestUtils testUtils = new TestUtils(); // Instantiate the tool class first Class cla = testUtils.getClass(); // Get class through object reflection Method[] methods = cla.getMethods(); // Get all the methods of this class if (methods != null && methods.length>0){ // Array non empty validation for (Method m:methods) { if (m.isAnnotationPresent(an4.class)){ // Determine whether the method has an4 this annotation. true if any. try { m.invoke(testUtils); // Call method }catch (Exception e){ bw.write("----Start collecting exceptions-------"); bw.newLine(); bw.write("Name of exception:"+e.getCause().getClass().getSimpleName()); bw.newLine(); bw.write("Abnormal information:"+e.getCause().getMessage()); bw.newLine(); bw.write("======Exception collection completed======="); bw.newLine(); bw.newLine(); count++; } } } try { bw.write("share"+count+"Exceptions"); }finally { if (bw != null){ // Closed flow bw.close(); } } } } }