URLClassLoader初体验

阅读更多
使用概要:
​File file = new File(jar文件全路径); 
​URL url = file.toURL(); 
​URLClassLoader loader = new URLClassLoader(new URL[] { url });
​Class tidyClazz = loader.loadClass(所需class的含包名的全名);

笔者案例:

URLClassLoader初体验_第1张图片

示例代码:

log4j.properties文件代码如下:
log4j.rootLogger=debug,appender1
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout


JarLoadUtil.java文件代码如下:
package com.shihuan.urlclassloader;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import org.apache.commons.lang.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JarLoadUtil {

	private static Logger logger = LoggerFactory.getLogger(JarLoadUtil.class);  
    private static URLClassLoader loader = null;
    
    /* 
     * 加载lib目录下所有jar文件,并返回相应的的URLClassLoader 
     */  
	public static URLClassLoader getURLClassLoader() {
		if (loader == null) {
			String fileNames[] = listFileNames();
			if (fileNames != null && fileNames.length > 0) {
				URL urls[] = new URL[fileNames.length];
				for (int i = 0; i < fileNames.length; i++) {
					try {
						StringBuilder sb = new StringBuilder();
						sb.append("file:").append(SystemUtils.FILE_SEPARATOR).append(System.getProperty("user.dir")).append(SystemUtils.FILE_SEPARATOR).append("lib");
						urls[i] = new URL(sb.toString() + SystemUtils.FILE_SEPARATOR + fileNames[i]);
					} catch (MalformedURLException e) {
						logger.error("加载lib目录下jar文件出错!", e);
						throw new RuntimeException("加载lib目录下jar文件出错!", e);
					}
				}
				loader = new URLClassLoader(urls);
			}
		}
		return loader;
	}  
	
    /* 
     * 查询lib目录下的所有文件名称 
     */  
	private static String[] listFileNames() {
		File file_directory = new File("lib");
		return file_directory.list();
	}  
	
}


TestUrlClassLoader.java文件代码如下:
package com.shihuan.test;

import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.logicalcobwebs.proxool.ProxoolDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shihuan.urlclassloader.JarLoadUtil;

public class TestUrlClassLoader {

	private static Logger logger = LoggerFactory.getLogger(TestUrlClassLoader.class);
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		URLClassLoader loader = JarLoadUtil.getURLClassLoader(); 
		
		ProxoolDataSource ds = new ProxoolDataSource();
		ds.setDriver("com.mysql.jdbc.Driver");
		ds.setDriverUrl("jdbc:mysql://localhost:3306/myword");
		ds.setUser("root");
		ds.setPassword("12345678");
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		Class clazz = null;
		try {
			clazz = loader.loadClass(ds.getDriver());
			Driver driver = (Driver)clazz.newInstance();          
            
			Properties p = new Properties();  
			p.put("user", ds.getUser());  
			p.put("password", ds.getPassword());       
			              
			conn = driver.connect(ds.getDriverUrl(), p);
			
			logger.info(conn.toString());
			
			String sql = "select id,name from mytaba";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getInt("id") + "  --  " + rs.getString("name"));
			}
			
			rs.close();
			pstmt.close();
			conn.close();
			
		} catch (ClassNotFoundException e) {
			logger.error(e.getMessage(), e);
		} catch (InstantiationException e) {
			logger.error(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			logger.error(e.getMessage(), e);
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} 
		
	}

}


运行TestUrlClassLoader.java文件中的main方法即可。



或者在dos窗口执行ant命令后进入%PROJECT_HOME%/dist/jar目录,执行java -jar myapp-${日期}.jar
  • URLClassLoader初体验_第2张图片
  • 大小: 17 KB
  • javapro.rar (1.8 MB)
  • 下载次数: 0
  • 查看图片附件

你可能感兴趣的:(URLClassLoader)