码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-04-11 16:23:59      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:rman   etc   trace   nec   定义   tty   rate   orm   gen   

一、自定义的注解

@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();
        }
        
    }
}

 

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

标签:rman   etc   trace   nec   定义   tty   rate   orm   gen   

原文地址:https://www.cnblogs.com/leduo-zuul/p/10690232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!