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 }
相關文章
相關標籤/搜索