I try to load dynamically a jar into my Java project.
Here's the class loader's code :
public class ClassLoad {
public static void main(String[] args) {
String filePath = new String("C:/Users/Mehdi/Desktop/JavaClassLoader/jarred.jar");
URL myJarFile = null;
try {
myJarFile = new URL("file://"+filePath);
} catch (MalformedURLException e1) {
System.out.println("1");
e1.printStackTrace();
}
URLClassLoader cl = URLClassLoader.newInstance(new URL[]{myJarFile});
Class Jarred = null;
try {
Jarred = cl.loadClass("com.jarred.exp.Jarred");
} catch (ClassNotFoundException e) {
System.out.println("2");
e.printStackTrace();
}
Method simpleWrite = null;
try {
simpleWrite = Jarred.getMethod("simpleWrite", new Class[] {String.class});
} catch (SecurityException e) {
System.out.println("3");
e.printStackTrace();
} catch (NoSuchMethodException e) {
System.out.println("4");
e.printStackTrace();
}
Object JarredObj = null;
try {
JarredObj = Jarred.newInstance();
} catch (InstantiationException e) {
System.out.println("5");
e.printStackTrace();
} catch (IllegalAccessException e) {
System.out.println("6");
e.printStackTrace();
}
try {
Object response = simpleWrite.invoke(JarredObj, "\nHello Mehdi ! It works hamdoulillah :D");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
and the Class which is included into the Jar :
package com.jarred.exp;
public class Jarred {
public void simpleWrite(String str) {
System.out.println(str);
}
}
It gives me :
2
java.lang.ClassNotFoundException: com.jarred.exp.Jarred
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.net.FactoryURLClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at ClassLoad.main(ClassLoad.java:25)
Exception in thread "main" java.lang.NullPointerException
at ClassLoad.main(ClassLoad.java:32)
Do you have any idea about this ? Thank you.
It looks like your file URL is invalid.
"File URIs in Windows" says
which shows that three slashes are needed after the colon, but the URL you are computing in
has only two slashes after the
file:
. Perhapsshould be
or alternatively you could use
java.io.File.toURI
thuswith appropriate exception handling.