I am trying to execute a function from a class in a jar file dynamically. I have the location of the jar file, the name of the class and the function in it as strings.
I looked at these questions, but none of the answers worked for me:
How should I load Jars dynamically at runtime?
ClassNotFoundException while trying to load class from external JAR at runtime
How to load a jar file at runtime
Load jar dynamically at runtime?
Here is what I've got so far: In the main program:
public class Main
{
public static void main(String[] args)
{
File file = new File("E:\\DeSKtop\\hw.jar");
String lcStr = "Main1";
URL jarfile;
try {
jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });
Class loadedClass = cl.loadClass(lcStr);
Method method = loadedClass.getDeclaredMethod("returnHW");
Object instance = loadedClass.newInstance();
Object result = method.invoke(instance);
//System.out.println(method.invoke());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(loadLibrary(myJar));
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In the jar file I'm trying to load:
public class Main1 {
public static void main(String[] args)
{
}
public static String returnHW()
{
System.out.println("HlloWOrld");;
return "Hello Wrld!";
}
}
When I try to run the main program I get this:
java.lang.ClassNotFoundException: Main1
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 Main.main(Main.java:22)
Can you tell me what I'm doing wrong? Thank you in advance.
the solution is that you have to state the packages as well.
If you update your variable lcStr where you store the classname to include the package, it shall work.
Example:
String lcStr = "com.company.Main1";