Home> Java> javaTutorial> body text

Type instance analysis of java annotations

王林
Release: 2023-05-01 20:31:12
forward
1484 people have browsed it

1. Custom annotation

Use keywords to define annotation: @interface

// #1 定义注解 public @interface MyAnno1{ }
Copy after login

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); } }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!