日期:2014-05-16 浏览次数:20514 次
public class MyClassLoaderTest implements MyClassLoaderTestInterface { public MyClassLoaderTest() { System.out.println("MyClassLoaderTest构造函数被调用了..."); } public void sayHello(String name) { System.out.println("Hello " + name + " 我是sayHello函数,我被调用了..."); } public class InnerClassTest { public InnerClassTest() {} public void print() { System.out.println("内部类"); } } }
package com.jvm.one.loadclassfromdb; public interface MyClassLoaderTestInterface { void sayHello(String name); }
package com.jvm.one.loadclassfromdb; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectDB { /** * 驱动程序名 */ private static final String driver = "com.mysql.jdbc.Driver"; /** * URL指向要访问的数据库名 */ private static final String url = "jdbc:mysql://localhost:3306/classloader_test?useUnicode=true&characterEncoding=UTF-8"; /** * 用户名 */ private static final String user = "root"; /** * 密码 */ private static final String password = "141421"; public static Connection getConnnection() { Connection conn = null; try { Class.forName(driver); //连接数据库 conn = DriverManager.getConnection(url, user, password); if (!conn.isClosed()) System.out.println("数据库连接成功..."); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { try { if (null != conn) conn.close(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } return conn; } public static void closeConnection(Connection conn) { try { if (null != conn) { conn.close(); System.out.println("数据库连接关闭..."); } else { System.out.println("数据库连接不存在..."); } } catch (SQLException e1) { e1.printStackTrace(); } } }
Class.forName(driver).newInstance()
static { try { java.sql.DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } }
public static Class<?> forName(String className) throws ClassNotFoundException { return forName0(className, true, ClassLoader.getCallerClassLoader()); }
private static native Class forName0(String name, boolean initialize, ClassLoader loader) throws ClassNotFoundException;
package com.jvm.one.loadclassfromdb; import java.io.FileInputStream; import java.io.FileNotFoundException; import j