Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

java - Load a class in a jar just with his name

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.

enter image description here

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what I tried, and I could make it work However it is advised to refer the 'javassist' jar for using ClassPool instead of ClassLoader

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


public class LoadTheClassFromJar {
public static void main(String[] args) throws IOException, ClassNotFoundException {
    String pathToJar = "E:\myjarfolder\MyProject.jar";
    String requiredClassName = "Hungry";
    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 = (JarEntry) e.nextElement();
            if(je.isDirectory() || !je.getName().endsWith(".class")){
                continue;
            }
            if (je.getName().contains(requiredClassName)){
                System.out.println(requiredClassName + " is found!"); 
            }
        // -6 because of .class
        String className = je.getName().substring(0,je.getName().length()-6);
        className = className.replace('/', '.');
        Class c = cl.loadClass(className);
        System.out.println(c.getName());
    }   
}
}

Output:

com.prash.MyClass
Hungry is found!
com.prash.Hungry

Note: I created my own jar file and dumped to that directory to test the program. I had a Hungry.java and MyClass.java in that project/jar file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...