Java annotations - learning Summary

Notes 1. Overview

1.1 notes explain

Note: The
        interpreted code, to the programmer
notes:
        the Java language classes, methods, variables, parameters, packages, etc., can be labeled. And different Javadoc, Java annotation label content can be obtained by reflection.
        When the compiler generates class files, annotation may be embedded bytecode.
        Java virtual machine can keep tagging content at runtime can get to the label content.
        Support for custom Java annotation
        feature after JDK1.5, for explaining the procedure, generally used in the frame
        format:
                @AnnotationName
documentation comments:
        @param, @return, @exception is fundamentally a comment, code compiler does not exist, generates .class byte code corresponding problem, only available to JavaDoc API document generation tool, as a marker to generate a corresponding document
annotation part involved in compiling
        @Override not have the effect of not compile, because [Eclipse] and [IDEA] [] can be pre-compiled Java code generation corresponding .class file

1.2 Role Notes

Generate a document:
        JavaDoc API documentation corresponding code generation
        @param @return
        [IDEA JavaDoc tool Parameters
                Other Command Line Arguments: -encoding utf- 8 -charset utf-8
                solve the Chinese garbled because IDEA default encoding set to UTF-8 Windows GBK
code checks:
        Inheritance rewritten, or interfaces to achieve compliance after, there @Override
code data acquisition: [] the small frame
        to get some content specified in the annotation by reflection, such as: configuration data, operation verification

1.3 Java predefined number of notes

@Override:
	【强制格式检查】重写/实现方法的情况下,检查方法声明 是否和父类或者接口中的方法声明一致。
@Deprecated
	标注当前方法已过时,例如: Data日期类内的一些方法
@SuppressWarnings("all")
	压制警告,可以用于一些代码中存在明确无异常的情况下,压制一些警告。

2. Java custom annotations

2.1 Java annotations in a custom way

format:

public @interface AnnotationName {
		属性列表;
}

        Annotation annotation can be obtained by compiling the corresponding .class byte code file [], [verify] There are some notes can be involved in the compilation process
decompile obtained:
        [Annotation Essence]
        public interface MyAnnotation1 extends java.annotation.Annotation {
}
         MyAnnotation1
                essentially an interface
        java.lang.annotation.Annotation
                subinterface
code demonstrates:

package xxx;

/**
 * 自定义注解!!!
 * public interface MyAnnotation1 extends java.lang.annotation.Annotation {
 * }
 *
 * @author Anonymous
 * @date 2020/3/10 11:01
 */
public @interface MyAnnotation1 {
    // 属性 ==> 方法形式
}

2.2 Annotation annotation attribute [difficult]

Properties:
        mode using annotations, the data attributes tend to use more concepts, but specific code formats in [Methods]. Actually use abstract methods to accomplish the concept of property.
Use properties:
        1. In writing code
                @MyAnnotation (id = 1, name = " strong", Age = 30)
        2. When using reflection, getXXX method involves
                obtaining values corresponding to the attribute name
format attributes for use: [ the method of operation according to the actual format]
        value of the data type and the corresponding specific properties 1. data ==> return value returns the type of data and
                attribute types supported:
                        . a basic data types
                        b.String type
                        c. other types of annotations.
                        D pieces. for type
                                enum is a constant with a name, and for better reading operation
                        e of the array corresponding to the above type.
                property values requirements:
                        . a keyword can be defined using the default attributes, plus a default value. Whereupon the default attribute in use, use the default values, or re-assignment.
                        b. If the annotation has only one attribute value, or in addition to annotation value attribute has a default value, regardless of class, method when the member variable, such as the use of the current annotation packages, can be added directly in parentheses correspond numeric types.
                        c. If the property is an array [] type, braces {} stored, and different content, with "," separated by
        the name of the key 2. The attribute name ==> Method

2.3 yuan notes

        To give an explanation of the annotation; annotated notes; a number of operational problems constraints annotations.
@Retention -
        identify how this annotation saved, only in code or incorporated into the class file, or can be accessed via reflection at runtime.
                RetentionPolicy.RUNTIME: current annotation will be compiled byte code corresponding .class files, and may be loaded into the JVM, involved in the implementation of the code
do not tangle, a note like:
        RetentionPolicy.SOURCE: annotation will be discarded (this type of compiler annotation information will only be retained in the source code, the source code after compiled, annotated information is discarded, does not remain in the compiled class files)
** ** @ Override
        corresponding property RetentionPolicy.SOURCE
        code compilation, inspection methods the correct format, the code does not participate in the operation and resolution.
@Documented
        mark these notes is contained in the user documentation.
        Is it possible to JavaDoc tool to generate the corresponding API documentation
@Target
        mark this comment should be a kind of Java members.
                Properties:
                        ElementType
                        the TYPE: current annotation can be used in the class declaration
                        METHOD: current annotation methods can be used to declare the position of
                        FIELD: current annotation can be used to declare member variables position
@Inherited
        mark this annotation is annotation class which inherits (default comment does not inherit any subclass)
[focus]
        @Target target
                role range: classes, methods, member variables ?????
        @Retention
                RetentionPolicy.RUNTIME common
Here Insert Picture Description

[Applications] 2.4 using a reflection acquire content of annotations

driverClass=com.mysql.jdbc.Driver
user=root
password=123456
url=jdbc:mysql://localhost:3306/db_name
# 配置文件保存到properties文件中,使用文件中内容读取配置获取属性
# properties Properties System.getProperties();
# Properties ==> driverClass ==> com.mysql.jdbc.Driver ==> 完整的包名.类名
# Class.forName 
package com.xxx;

import com.xxx.Person;

import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

/**
 * 解析properties文件读取内容,使用反射创建对象,赋值成员变量
 *
 * @author Anonymous
 */
public class ReflectFile {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("./src/1.properties"));

        String className = properties.getProperty("className");
        String id = properties.getProperty("id");
        String name = properties.getProperty("name");
        System.out.println(className);
        Class<?> aClass = Class.forName(className);

        Person person = (Person) aClass.getConstructor().newInstance();

        System.out.println(person);

        Field declaredField = aClass.getDeclaredField("id");
        declaredField.setAccessible(true);
        declaredField.set(person, Integer.parseInt(id));

        Field declaredField2 = aClass.getDeclaredField("name");
        declaredField2.setAccessible(true);
        declaredField2.set(person, name);

        System.out.println(person);
    }
}
package com.xxx;
import com.xxx.MyAnnotation.MyAnnotation5;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 通过注解方式,获取注解的属性,创建对象,读取数据
 * 通常用于代码配置
 *      Servlet Listener Filter
 * @author Anonymous
 */
@MyAnnotation5(className = "com.qfedu.a_annotation.Person",
        id = 2,
        name = "骚磊")
public class ReflectAnnotatiaon {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        // 加载ReflectAnnotatiaon
        Class<ReflectAnnotatiaon> cls = ReflectAnnotatiaon.class;

        // 因为注解是在类名之上,通过Class获取对应的Annotation
        MyAnnotation5 annotation = cls.getAnnotation(MyAnnotation5.class);
        /*
        类似于注解的实现类
        class XXX implements MyAnnotation5 {
            public String className() {
                return "com.qfedu.a_annotation.Person";
            }
            public int id() {
                return 2;
            }
            public String name() {
                return "骚磊";
            }
        }
         */
        // 感觉是在执行对应的方法,获取注解的属性
        String s = annotation.className();
        int id = annotation.id();
        String name = annotation.name();

        System.out.println(s);
        System.out.println(id);
        System.out.println(name);

        Class<?> aClass = Class.forName(s);

        Constructor<?> constructor = aClass.getConstructor(Integer.class, String.class);

        Object o = constructor.newInstance(id, name);
        System.out.println(o);
    }
}

2.5 annotations using code running test [Use]

package com.xxx.checkMethod;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 没有任何的属性,只是作为是否需要测试的标记
 *
 * @author Anonymous
 */
// 注解有且只能用于方法上
@Target(ElementType.METHOD)
// 参与编译和运行
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {
}
package com.xxx.checkMethod;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 测试Tools类内的方法,如果方法带有Check注解,执行测试,记录异常
 *
 * @author Anonymous
 */
@ClassAnnotation(className = "com.qfedu.a_annotation.checkMethod.Utils")
public class TestProject {
    public static void main(String[] args)
            throws IOException, InvocationTargetException,
            IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InstantiationException {

        // 从注解中获取对应的属性
        Class<TestProject> cls  = TestProject.class;
        ClassAnnotation annotation = cls.getAnnotation(ClassAnnotation.class);
        String s = annotation.className();
        Class<?> aClass = Class.forName(s);

        Object tools = aClass.getConstructor().newInstance();
        // 获取所有Tools类内的方法,不包括父类方法
        Method[] declaredMethods = aClass.getDeclaredMethods();

        // 出现错误的次数
        int count = 0;
        long l = System.currentTimeMillis();
        BufferedWriter br = new BufferedWriter(new FileWriter("./src/log.txt"));

        // 遍历方法数组
        for (Method declaredMethod : declaredMethods) {
            declaredMethod.setAccessible(true);

            // 判断当前方法是否带有注解@Check,标记
            if (declaredMethod.isAnnotationPresent(Check.class)) {
                try {
                    // 执行方法
                    declaredMethod.invoke(tools);
                } catch (Exception e) {
                    count += 1;

                    // 1. 哪一个方法出现异常
                    br.write("方法:" + declaredMethod.getName());
                    br.newLine();
                    // 2. 发生什么异常 获取原因,获取对应的类型
                    br.write("异常类型:" + e.getCause().getClass().getSimpleName());
                    br.newLine();
                    // 3. 异常信息
                    br.write("异常信息:" + e.getCause().getMessage());
                    br.newLine();
                    br.write("-----------------------------------------------------------------");
                    br.newLine();
                }
            }
        }

        long l1 = System.currentTimeMillis();
        br.write("出现错误的次数:" + count);
        br.newLine();
        br.write("总耗时:" + (l1 - l));
        br.newLine();

        br.close();
    }
}

3. Use annotations summary

        1. After most cases, there are notes about the use of the process, rather than custom. It will be used to frame the pretreated annotations.
        2. The use of annotations to whom?
                a. compiler
                B. parsing code using
                c.JVM is a label, sometimes marked, sometimes there is a label attribute.

4. Framework

MySQL database
        Java connect to the MySQL
        driver, database user name, password, specified database ...
        every operation requires a programmer yourself, a lot of trouble! ! !

Provide a template
        for preparing the data connection to the database you use.

Database operations
        CRUD
        resource processing
        the data analysis
        connection object is closed

Provides a solution
        CRUD SQL statements
        and the corresponding parameters on OK

Framework is a semi-finished project, the business logic requires the programmer to complete the complicated operation is completed frame.
        JDBC -> JDBCUtils -> DBUtils - > MyBatis -> MyBatis-plus

Published 22 original articles · won praise 36 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41986648/article/details/104780626