Java annotation (Java advanced)

Mind mapping

1. Notes overview

  • What is Annotation: what is Annotation: Annotation annotation is a code level specification. It is a feature introduced by JDK 1.5 and later, which is at the same level as class, interface and enumeration

  • Role of annotation: mainly used to replace XML and properties configuration files

2. Notes provided by JDK

  • @Override: used on a method to indicate that the method overrides the method of the parent class, such as toString(). If the parent class does not have this method, it cannot be compiled.

    //#2.1 JDK5.0 replication parent method
    class Parent1_2{
    public void init(){
    }
    }
    class Son1_2 extends Parent1_2{
    @Override
    public void init() {
    }
    }
    
    //#2.2 implementation of parent interface method in JDK6.0
    interface Parent1_3{
    public void init();
    }
    class Son1_3 implements Parent1_3{
    @Override
    public void init() {
    }
    }
    
  • @Deprecated: indicates that this method has expired and is not recommended for developers. (suggesting that some uncertain version may be cancelled in the future)

    //#1 method expired
    class Parent1_1{
    @Deprecated
    public void init(){
        }
    }
    
  • @SuppressWarnings: indicates that warnings are suppressed. The purpose of this annotation is to ignore warnings.

    • deprecation, ignoring obsolescence
    • rawtypes, ignoring type security
    • unused, ignore not used
    • unchecked, ignore security check
    • Null, ignore null
    • All, ignore all
    //#3 suppress warning
    // Serial: implements the serial number interface, but does not have a production serial number
    @SuppressWarnings("serial")class Parent1_4 implements java.io.Serializable{
    //Null: null pointer
    @SuppressWarnings("null")
    public void init(){
         //rawtypes: type safe, no generics used
         //unused: not used
        @SuppressWarnings({ "rawtypes", "unused" })
        List list = new ArrayList();
        String str = null;
        str.toString();
         }
    }
    
  • @SafeVarargs: when using Variable number of parameters When the parameter type is generic T, a warning will appear.

    public class Hero {
        String name;
    
        @SafeVarargs
        public static <T> T getFirstOne(T... elements) {
            return elements.length > 0 ? elements[0] : null;
        }
    }
    
  • @Functional interface: used to contract functional interfaces.

    Functional interface concept: if there is only one abstract method in an interface (which can contain multiple default methods or multiple static methods), the interface is called a functional interface. The significance of functional interface is mainly cooperation Lambda expression To use.

    @FunctionalInterface
    public interface AD {
        public void adAttack();
    }
    

3. Custom annotation

  • Define annotation using keyword: @ interface

    // #1 definition notes
    public @interface MyAnno1{
    }
    

3.1 definition - meta notes

  • Meta annotation: annotation used to modify annotation.
    • Metadata: data that provides information for other data

abstract

Note type summary
Documented Indicates that a type of comment will be documented with javadoc and similar default tools
Inherited Indicates that the comment type is automatically inherited
Retention Indicates how long comments of the comment type are to be retained
Target Indicates the type of program element to which the comment type applies
@Repeatable Indicates that the annotation is in the same position and can be used multiple times
Enumeration Digest
ElementType Program element type
RetentionPolicy Comment retention policy

There are five meta annotations provided by JDK:

  • @Target: used to determine where the decorated custom annotation is used

    • ElementType.TYPE decorated class, interface
    • ElementType.CONSTRUCTOR: decorated construction
    • ElementType.METHOD: decorated method
    • ElementType.FIELD: decorated field
    • ElementType.PARAMETER: decorated parameter
    • Elementtype.local'variable: decorated local variable
    • Elementtype.annotation'type: decorated annotation
    • ElementType.PACKAGE: decoration package
    package anno;
    
    import static java.lang.annotation.ElementType.METHOD;
    import static java.lang.annotation.ElementType.TYPE;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({METHOD,TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface JDBCConfig {
         String ip();
         int port() default 3306;
         String database();
         String encoding();
         String loginName();
         String password();
    }
    
  • @Retention: used to determine the decorated custom annotation lifecycle

    • RetentionPolicy.SOURCE: the modified annotation can only exist in the source code, but not compiled into bytecode class. For example: @ Override
    • RetentionPolicy.CLASS: the modified annotation can only exist in source code and bytecode, but not in runtime memory.
    • RetentionPolicy.RUNTIME: the decorated annotation still exists after running, and the program can obtain this information through reflection.
    package anno;
    
    import static java.lang.annotation.ElementType.METHOD;
    import static java.lang.annotation.ElementType.TYPE;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({METHOD,TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface JDBCConfig {
         String ip();
         int port() default 3306;
         String database();
         String encoding();
         String loginName();
         String password();
    }
    
  • @Inherited: indicates that the annotation is inherited

    package util;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    import anno.JDBCConfig;
    
    public class DBUtilChild extends DBUtil {
    
        public static Connection getConnection2() throws SQLException, NoSuchMethodException, SecurityException {
            JDBCConfig config = DBUtilChild.class.getAnnotation(JDBCConfig.class);
            String ip = config.ip();
            int port = config.port();
            String database = config.database();
            String encoding = config.encoding();
            String loginName = config.loginName();
            String password = config.password();
    
            String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s", ip, port, database, encoding);
            return DriverManager.getConnection(url, loginName, password);
        }
    
        public static void main(String[] args) throws NoSuchMethodException, SecurityException, SQLException {
            Connection c = getConnection2();
            System.out.println(c);
        }
    }
    
  • @Documented: whether to include this annotation when generating api documents using javadoc (learn)

  • @Repeatable: the annotation is in the same location and can only appear once. You can use @ repeatable multiple times in the same place.

    package util;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    import anno.JDBCConfig;
    
    @JDBCConfig(ip = "127.0.0.1", database = "test", encoding = "UTF-8", loginName = "root", password = "admin")
    @JDBCConfig(ip = "127.0.0.1", database = "test", encoding = "UTF-8", loginName = "root", password = "admin")
    public class DBUtil {
        static {
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    
        public static Connection getConnection() throws SQLException, NoSuchMethodException, SecurityException {
            JDBCConfig config = DBUtil.class.getAnnotation(JDBCConfig.class);
            System.out.println(config);
    
            String ip = config.ip();
            int port = config.port();
            String database = config.database();
            String encoding = config.encoding();
            String loginName = config.loginName();
            String password = config.password();
    
            String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s", ip, port, database, encoding);
            return DriverManager.getConnection(url, loginName, password);
        }
    
        public static void main(String[] args) throws NoSuchMethodException, SecurityException, SQLException {
            Connection c = getConnection();
            System.out.println(c);
        }
    }
    

Tags: Programming Java Database encoding SQL

Posted on Sat, 04 Apr 2020 02:19:33 -0700 by moltenice