自定义注解以及通过反射获取注解

一、自定义的注解

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface jdbcConfig {
    String ip();
    int port() default 3306;
    String database();
    String encoding();
    String username();
    String password();
}

二、通过反射获取注解信息

@jdbcConfig(ip="127.0.0.1",database="test",encoding="UTF-8",username="root",password="admin")
public class AnnotationDButil {
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static Connection getConnection() throws SQLException {
        //通过反射获取注解信息
        jdbcConfig annotation = AnnotationDButil.class.getAnnotation(jdbcConfig.class);
        String ip = annotation.ip();
        int port = annotation.port();
        String database = annotation.database();
        String username = annotation.username();
        String password = annotation.password();
        String encoding = annotation.encoding();
        String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=%s", ip,port,database,encoding);
        return DriverManager.getConnection(url, username, password);
    }
    
    public static void main(String[] args) {
        try {
            Connection c = getConnection();
            System.out.println(c);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

 

三、基本注解详解
@Target表示注解能放在什么位置上
ElementType.TYPE:能修饰类、接口或枚举类型
ElementType.FIELD:能修饰成员变量
ElementType.METHOD:能修饰方法
ElementType.PARAMETER:能修饰参数
ElementType.CONSTRUCTOR:能修饰构造器
ElementType.LOCAL_VARIABLE:能修饰局部变量
ElementType.ANNOTATION_TYPE:能修饰注解
ElementType.PACKAGE:能修饰包

@Retention 表示生命周期

自定义注解@JDBCConfig 上的值是 RetentionPolicy.RUNTIME, 表示可以在运行的时候依然可以使用。 @Retention可选的值有3个:
RetentionPolicy.SOURCE: 注解只在源代码中存在,编译成class之后,就没了。@Override 就是这种注解。
RetentionPolicy.CLASS: 注解在java文件编程成.class文件后,依然存在,但是运行起来后就没了。@Retention的默认值,即当没有显式指定@Retention的时候,就会是这种类型。
RetentionPolicy.RUNTIME: 注解在运行起来之后依然存在,程序可以通过反射获取这些信息,自定义注解@JDBCConfig 就是这样。

@Inherited 表示该注解具有继承性。

@Documented
在用javadoc命令生成API文档后,该类的文档里会出现该注解说明。

@Repeatable 在一个类中可重复的使用一个注解(需要其他注解制定)

转载于:https://www.cnblogs.com/leduo-zuul/p/10690232.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值