博客年龄:17年6个月
访问:?
文章:291篇

个人描述

姓名:丹臣 职业:DBA 公司:TAOBAO Mail:zhaolinjnu(at)163.com MSN:echo_lin@hotmail.com 微博http://twitter.com/zhaolinjnu

URLClassLoader的用处

分类:Java | 标签: java   容器   隔离  
2013-07-18 11:49 阅读(?)评论(0)
最近在看潘多拉容器,这个容器主要解决二方包升级,以及二方包所依赖的三方包冲突的问题。为了解决冲突,主要是利用urlclassloader来完成隔离的目标的。下面来看看urlclassloader为何物?
public class URLClassLoader
extends SecureClassLoader
implements Closeable
This class loader is used to load classes and resources from a search path of URLs referring to both JAR files and directories. Any URL that ends with a '/' is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be opened as needed.

The AccessControlContext of the thread that created the instance of URLClassLoader will be used when subsequently loading classes and resources.

The classes that are loaded are by default granted permission only to access the URLs specified when the URLClassLoader was created.


详细的URLClassLoader介绍:http://docs.oracle.com/javase/7/docs/api/java/net/URLClassLoader.html


下面是一个测试用例:

package com.taobao.danchen.classloader;

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

public class TestURLClassLoader {

/**
* @param args
* @throws Exception 
*/
public static void main(String[] args) throws Exception {
String pathString="D:\\java\\sqlautoreview\\target\\sqlautoreview-1.0-SNAPSHOT.jar";
File file = new File(pathString);
if(!file.exists() || file.isDirectory()){
throw new Exception("jar file is not exist.or file is a directory.");
}
URL[] urls = new URL[]{file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
        Class<?> class1;
try {
class1 = loader.loadClass("com.taobao.sqlautoreview.structure.ColumnNode");
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
System.out.println(class1.getName()+" is loaded success.");
        Object object = class1.newInstance();
        System.out.println(object);
}

}

如果把应用所依赖的二方包,及二方包所依赖的其它jar包都放在容器的一个目录下,对外只暴露应用需要类即可。在我们的环境里,潘多拉容器与jboss的容器是关联在一起的,需要把潘多拉容器里需要导出的类,放到jboss容器的Cache里,这样应用就可以看到了。
 
表  情:
加载中...
 

请各位遵纪守法并注意语言文明