Created
June 19, 2018 03:47
-
-
Save MrMaurice211/2c8643315219cc6eef5020640b5efff7 to your computer and use it in GitHub Desktop.
Basic Module System
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 static void main(String[] args) { | |
File folder = new File(".", "modules"); | |
List<Class<?>> clazzez = Lists.newArrayList(); | |
for (File file : folder.listFiles()) | |
try { | |
Class<?> clazz = getModule(file); | |
if (clazz != null) | |
clazzez.add(clazz); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
for (Class<?> clazz : clazzez) { | |
Module m = clazz.getAnnotation(Module.class); | |
System.out.println(m.name()); | |
System.out.println(m.author()); | |
System.out.println(m.version()); | |
try { | |
clazz.newInstance(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
public static Class<?> getModule(File file) { | |
try (JarFile jarFile = new JarFile(file)) { | |
Enumeration<JarEntry> en = jarFile.entries(); | |
URLClassLoader child = new URLClassLoader(new URL[] { file.toURI().toURL() }, getClass().getClassLoader()); | |
while (en.hasMoreElements()) { | |
JarEntry next = en.nextElement(); | |
String name = next.getName(); | |
if (name.endsWith(".class")) { | |
name = name.replace('/', '.'); | |
Class<?> clazz = Class.forName(name.substring(0, name.length() - 6), true, child); | |
if (clazz.getAnnotation(Module.class) != null) | |
return clazz; | |
} | |
} | |
} catch (IOException | ClassNotFoundException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment