1\annotation 写法
package com.gyarmy.testannotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface DbInfo { String driverClass(); String username(); String password(); String url(); }
2\ 使用annotation
package com.gyarmy.testannotation; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; import org.junit.Test; public class JdbcUtils { @Test public void test1() throws Exception { Connection c1 = getConnection(); System.out.println(c1); } @DbInfo(driverClass="com.mysql.jdbc.Driver",username="root",password="luobo360",url="jdbc:mysql://localhost/test002") public Connection getConnection() throws Exception{ Class clazz = Class.forName("com.gyarmy.testannotation.JdbcUtils"); Method method = clazz.getMethod("getConnection", null); boolean isPresent = method.isAnnotationPresent(DbInfo.class); System.out.println(isPresent); if(isPresent){ DbInfo annotation = method.getAnnotation(DbInfo.class); String driverClass = annotation.driverClass(); String username = annotation.username(); String password = annotation.password(); String url = annotation.url(); //注册驱动 Class.forName(driverClass); //获得连接 Connection connection = DriverManager.getConnection(url, username, password); return connection; } return null; } }
0则评论给“annotation简单测试”