Use urlclassloader to dynamically load all jar files in the specified path

Source: Internet
Author: User

Package test. tool. Gui. dbtool. util;

Import java. Io. file;
Import java.net. malformedurlexception;
Import java.net. url;
Import java.net. urlclassloader;
Import org. Apache. log4j. Logger;
Import test. tool. Gui. dbtool. consts. const;

Public class jarloadutil {

Private Static logger log = logger. getlogger (jarloadutil. Class );
Private Static URL lib_url = classloader. getsystemclassloader (). getresource ("lib ");
Private Static urlclassloader loader = NULL;
/*
* Load all jar files in the lib directory and return the corresponding 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 {
URLs [I] = new URL (lib_url + "/" + filenames [I]);
} Catch (malformedurlexception e ){
If ("true". Equals (configutil. getconfinfo (). Get (Const. is_log) + "")){
Log. Error ("An error occurred while loading the JAR file in the lib directory! ", E );
}
Throw new runtimeexception ("An error occurred while loading the JAR file in the lib directory! ", E );
}
}
Loader = new urlclassloader (URLs );
}
}
Return loader;
}
/*
* Query the names of all files in the lib directory.
*/
Private Static string [] listfilenames (){
File file_directory = new file ("lib ");
Return file. List ();
}
}

 

Usage:

 

Urlclassloader loader = jarloadutil. geturlclassloader ();
Class <?> Clazz = loader. loadclass (Ds. getdriverclassname ());
Driver driver = (driver) clazz. newinstance ();

Properties P = new properties ();
P. Put ("user", DS. GetUserName ());
P. Put ("password", DS. getpwd ());

Connection con = driver. Connect (Ds. geturl (), P );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.