I tried to load a class within a jar, without success.
URL url = null;
try {
url = new URL("jar:file:"+System.getProperty("user.dir")+File.separator+"games"+File.separator+gameName+"!/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL[] urls = {url};
URLClassLoader cl = URLClassLoader.newInstance(urls);
try {
String gameClassPath = null;
JarFile jar = new JarFile(url.getPath().replace("file:", "").replace("!", ".jar"));
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().contains(gameName)) {
gameClassPath = entry.getName().replace('/', '.').replace(".class", "");
}
}
this.gameClass = cl.loadClass(gameClassPath);
jar.close();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
I think the problem is coming from the URLClassLoader
which may not be at the right place.
Editing the question with the OP's updates[posted in answer section]
I still have error with @spiderman version.
I precise that gameClass type is Class<?>
, not Class
, but I don't know the difference.
String pathToJar = System.getProperty("user.dir")+File.separator+"games"+File.separator+gameName;
String requiredClassName = gameName;
JarFile jarFile = new JarFile(pathToJar+".jar");
Enumeration<JarEntry> e = jarFile.entries();
URL[] urls = {new URL("jar:file:"+pathToJar+"!/")};
URLClassLoader cl = URLClassLoader.newInstance(urls);
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if(je.isDirectory() || !je.getName().endsWith(".class")){
continue;
}
if (je.getName().contains(requiredClassName)){
System.out.println(requiredClassName + " is found!");
}
String className = je.getName().substring(0,je.getName().length()-6);
className = className.replace('/', '.');
gameClass = cl.loadClass(className);
}
jarFile.close();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…