I am loading the classes of a Jar file...now I want to invoke the Main-method. I did find the Method but when calling invoke it says: NoSuchMethodException
.
Here is my Code:
@SpringBootApplication
public class Uebung2Application {
public static void main(String[] args) {
SpringApplication.run(Uebung2Application.class, args);
}
@PostConstruct
public void start() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
try {
String pathToJar = "test.jar";
JarFile jarFile = new JarFile(pathToJar);
Enumeration<JarEntry> e = jarFile.entries();
URL[] urls = { new URL("jar:file:" + pathToJar+"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
if(je.isDirectory() || !je.getName().endsWith(".class")){
continue;
}
// -6 because of .class
String className = je.getName().substring(0,je.getName().length()-6);
className = className.replace('/', '.');
Class c = cl.loadClass(className);
Arrays.asList(c.getMethods()).forEach(m ->
System.out.println(m.toString()));
if(Arrays.asList(c.getMethods()).stream().anyMatch(m -> m.getName().equals("main"))) {
System.out.println(className);
c.getDeclaredMethod("main").invoke(null, new String[] {"1", "2"});
}
}
}catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
Aucun commentaire:
Enregistrer un commentaire