Class.forName()与newInstance()

 1 import java.sql.Connection;
 2 import java.sql.DriverManager;
 3 import java.sql.ResultSet;
 4 import java.sql.Statement;
 5 import java.util.Date;
 6 
 7 
 8 public class NewInstanceExample {
 9 
10     public static void main(String[] args) throws Exception {
11         //Class.forName()要求JVM查找并加载指定的类
12         //newInstance()获取类的实例
13         //newInstance()方法和new关键字区别:一个是方法,一个是关键字,newInstance()只能调用无参的构造函数
14         //forName和newInstance获得更好的灵活性,提供了一种降耦的手段
15         Date date = java.util.Date.class.newInstance();
16         long time = date.getTime();
17         System.out.println(time);
18         
19         Class<?> dateClass = Class.forName("java.util.Date");
20         Date date2 = (Date) dateClass.newInstance();
21         long time2 = date2.getTime();
22         System.out.println(time2);
23         
24         mysqlConnection();
25         
26     }
27     
28     public static void mysqlConnection() throws Exception {
29         //在JDBC规范中明确要求Driver类必须向DriverManager注册自己
30         //类似如下:
31         /*
32         public class MyJDBCDriver implements Driver {
33             static {
34                 DriverManager.registerDriver(new MyJDBCDriver());
35             }
36         }
37         */
38         //Class.forName()在加载com.mysql.jdbc.Driver时,会执行静态代码块,向DriverManager注册自己
39         Class.forName("com.mysql.jdbc.Driver");
40         String url = "jdbc:mysql://localhost/test?useUnicode=true&&characterEncoding=UTF-8&autoReconnect=true";
41         String user = "root";
42         String password = "123456";
43         
44         Connection conn = null;  
45         Statement stmt = null;  
46         ResultSet rs = null;  
47         try {  
48             conn = DriverManager.getConnection(url, user, password);
49             stmt = conn.createStatement();
50             String sql = "select deptno,deptname from dept";// dept这张表有deptno,deptname字段
51             rs = stmt.executeQuery(sql);// 执行sql语句
52             while (rs.next()) {
53                 System.out.print(rs.getInt("deptno") + "    ");
54                 System.out.println(rs.getString("deptname"));
55             }
56         } catch (Exception e) { 
57             throw e;
58         } finally {
59             rs.close();
60             stmt.close();
61             conn.close();
62         }  
63     }
64 }

 

posted on 2016-08-20 23:48  guodefu909  阅读(326)  评论(0编辑  收藏  举报

导航