I have a jar file which I runs fine with java -jar my-jar-file.jar
.
But now I have to load the main class from another java program using reflection and when I do that I get a ClassNotFoundException: javax.mail.MessagingException
.
The code I'm using to do that:
URLClassLoader loader = URLClassLoader.newInstance(new URL[]{new File("my-jar-file.jar").toURI().toURL()});
Class<?> serverClass = loader.loadClass("com.foo.bar.application.MyMain");
Method main = serverClass.getMethod("main", String[].class);
String[] params = new String[]{"-flag", "value"};
main.invoke(null, (Object) params);
The stacktrace is like this (removed details):
Exception in thread "main" java.lang.reflect.InvocationTargetException
Caused by: java.lang.NoClassDefFoundError: javax/mail/MessagingException
Caused by: java.lang.ClassNotFoundException: javax.mail.MessagingException
I also tried adding entries from System.getProperty("java.class.path")
to the array of URL
s I pass to class loader, but no luck as well.
This error seems reasonable to me as the jar file does not contain javax.mail.MessagingException
(does not contain javax.mail
package actually) but how does it work when I just do java -jar my-jar-file.jar
?
How can I fix this issue? Thanks
edit:
Added MANIFEST.MF contents:
Manifest-Version: 1.0
Main-Class: com.foo.bar.application.MyMain
Implementation-Version: 1.5.4
edit 2:
One more thing worth to mention is that the jar file contains a javamail.providers
file in META-INF
directory. Suppose this somehow makes that jar to work, but how can I do the same programmatically?
javamail.providers
contents:
# AWS Mail Provider
protocol=aws; type=transport; class=com.amazonaws.services.simpleemail.AWSJavaMailTransport; vendor=Amazon Web Services LLC;