Home >Java >javaTutorial >Type instance analysis of java annotations
1. Custom annotation
Use keywords to define annotation: @interface
// #1 定义注解 public @interface MyAnno1{ }
2. Meta annotation
Annotations used to modify annotations.
Five kinds of meta-annotations provided by JDK:
(1) @Target: used to determine the location of modified custom annotations
(2) @Retention: used To determine the life cycle of the modified custom annotation
(3) @Inherited: Indicates that the annotation has inheritance (understanding)
(4) @Documented: When using javadoc to generate api documentation, Whether to include this annotation (understand)
(5) @Repeatable: The annotation is in the same position and can only appear once. With @Repeatable, you can use it 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); } }
The above is the detailed content of Type instance analysis of java annotations. For more information, please follow other related articles on the PHP Chinese website!