如何在编译之前从外部JAR加载一个我不知道的类?
问题归结为,"如何在jar中获取课程的路径?"
try {
for (int x = 0; x < new File("mods").listFiles().length; x++) {
if (new File("mods").listFiles()[x].getName().endsWith(".jar")) {
JarFile file = new JarFile(new File("mods").listFiles()[x].getPath());
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().endsWith(".class")) {
new URLClassLoader(new URL[]{new URL("file://"+new File("mods").listFiles()[x].getAbsolutePath())}).loadClass(%path-to-class%);
}
}
file.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:1)
也许试试这个。
try
{
// Get all the files in mod folder
File[] mods = new File("mod").listFiles();
for (int i=0; i<mods.length; i++)
{
// Skip if the file is not a jar
if (!mods[i].getName().endsWith(".jar"))
continue;
// Create a JarFile
JarFile jarFile = new JarFile(mods[i]);
// Get the entries
Enumeration e = jarFile.entries();
// Create a URL for the jar
URL[] urls = { new URL("jar:file:" + mods[i].getAbsolutePath() +"!/") };
cl = URLClassLoader.newInstance(urls);
while (e.hasMoreElements())
{
JarEntry je = (JarEntry) e.nextElement();
// Skip directories
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('/', '.');
// Load the class
Class c = cl.loadClass(className);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
希望这有帮助。