1、JDK 5.0 在 java.lang.reflect 包下新增了Annotation 接口, 该接口表明程序中能够接受注解。java
当一个Annotation 类型被定义为运行时Annotation 后, 该注释才是运行时可见, 当 class 文件被载入时保存在 class 文件中的 Annotation 才会被虚拟机读取。mysql
以前咱们的一些配置信息都写在xml文件中,而后在经过解析XML文件,拿到咱们想要的数据。有了Annotation 以后,它能够代替XML。咱们能够给程序加注解来配置一些信息,就像使用XML同样,配置了数据以后,还须要解析注解拿到咱们配置的数据。sql
代码(定义一个注解):url
//在定义注解时,必定不要忘了要配置这个元注解,若是不加,再取注解数据时,程序定报空指针 (这个元注解是将DbInfo这个注解标示为运行时注解) @Retention(RetentionPolicy.RUNTIME) public @interface DbInfo { String url(); String username(); String password(); }
代码(为程序加入注解,在读取注解数据):spa
public class JdbcUtils { @DbInfo(url="jdbc:mysql://localhost:3306/test",username="root",password="root") public static Connection getConnection() throws SecurityException, NoSuchMethodException{ //经过反射来解析注解 Class clazz = JdbcUtils.class; Method method = clazz.getMethod("getConnection", null); //拿到注解以后,就能够获取注解的数据了 DbInfo info = method.getAnnotation(DbInfo.class); System.out.println(info.url());//jdbc:mysql://localhost:3306/test System.out.println(info.username());//root System.out.println(info.password());//root return null; } public static void main(String[] args) throws SecurityException, NoSuchMethodException { getConnection(); } }