Link to home
Start Free TrialLog in
Avatar of spectrumsofttech
spectrumsofttechFlag for India

asked on

Dynamically add jar file to the class path

 File jarDir = new File(jarPath);
		        ArrayList<URL> jarFiles = new ArrayList<URL>();

		        for(File file: jarDir.listFiles())
		        {
		            if(file.isFile() && file.getName().endsWith(".jar"))
		            {
		                jarFiles.add(file.toURI().toURL());
		            }
		        }

		        for(URL url:jarFiles)
		            System.out.println(url);

		        URL[] urlArray = new URL[jarFiles.size()];
		        for(int i=0; i<jarFiles.size(); i++)
		            urlArray[i] = jarFiles.get(i);

		        ClassLoader  loader = new URLClassLoader(urlArray);

Open in new window


I'm using the above code to load the jar from external source. But, I'm not able to include the jar into my class path.

For example,

I can load mysqlconnector.jar from any external source. But, when I use the statement,
Class.forName ("com.mysql.jdbc.Driver");

Open in new window


It gives an exception

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Is there a way to include the external jar into my application class path?
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Firstly, can we ask, why are you not able to add the path of 'jarDir' prior to vm startup?

fyi, there's nothing wrong with your code
Avatar of spectrumsofttech

ASKER

I've an application, which will load an external class. That class may be dependent on the jar files say for example "mysqlconnector.jar" that may not be present in the application.  So when I load that class, I'll also load the jar on which the external class dependent.
ASKER CERTIFIED SOLUTION
Avatar of mccarl
mccarl
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
fyi, there's nothing wrong with your code
Sorry spectrumsofttech. I managed to fail to connect the outcome with your code. There IS nothing wrong with your code, but you should try, after running it, to do what mccarl suggested (who has not had the same problem as i connecting the code with the outcome ;))