Created
September 22, 2017 00:41
-
-
Save tom-code/7e3c62ff7a32df5b9289647c5ba7bc20 to your computer and use it in GitHub Desktop.
instantiate classes from jar based on annotation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) { | |
load("test/1.jar"); | |
load("test/2.jar"); | |
} | |
private static void load(String path) { | |
try { | |
ClassLoader cl = new URLClassLoader(new URL[] { new File(path).toURL()}); | |
JarFile jarFile = new JarFile(path); | |
Enumeration<JarEntry> entries = jarFile.entries(); | |
while (entries.hasMoreElements()) { | |
JarEntry entry = entries.nextElement(); | |
if (!entry.getName().endsWith(".class")) continue; | |
System.out.println(entry); | |
String className = entry.getName().substring(0, entry.getName().length()-6); | |
System.out.println("classname " + className); | |
Class<?> c = cl.loadClass(className); | |
Service sa = c.getAnnotation(Service.class); | |
if (sa == null) continue; | |
Object o = c.newInstance(); | |
Method m = c.getDeclaredMethod("execute"); | |
System.out.println("=====executing path="+sa.path()); | |
m.invoke(o); | |
System.out.println("====="); | |
} | |
} catch (IOException | ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment