0

我正在尝试从文件系统上的路径中获取一个类,并从中获取字节。我已经尝试过下面的内容,但没有成功。现在应该只打印出名称。如果有人对如何做我正在做的事情有任何想法,请告诉我。它甚至可能比这更容易......

public class Driver {
public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter the path of the class:  ");
    String from = br.readLine();
    System.out.print("Enter the path to save the .txt file (with bytes):  ");
    String to = br.readLine();
    Class clazz = getClassFromPath(from);
    System.out.println("Loaded <" + clazz.getName() + "> successfully!");
}

public static Class<?> getClassFromPath(String path) {
    try {
        File file = new File(path);
        URL[] urls = {new URL(path)};
        URLClassLoader cl = URLClassLoader.newInstance(urls);
        if (!file.isDirectory() && file.getName().endsWith(".class")) {
            String className = file.getName().substring(0, file.getName().length() - 6);
            className = className.replace('/', '.');
            Class c = cl.loadClass(className);
            return c;
        }
        for (File f : file.listFiles()) {
            if (f.isDirectory() || !f.getName().endsWith(".class")) {
                continue;
            }
            String className = f.getName().substring(0, f.getName().length() - 6);
            className = className.replace('/', '.');
            Class c = cl.loadClass(className);
            return c;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}
}
4

1 回答 1

3

我很确定你可以尝试这样的事情:

InputStream stream = clazz.getClassLoader().getResourceAsStream(classAsPath);

其中classAsPath是您在方法getClassFromPath上实际执行的操作

然后你可能想使用 Apache Commons-io 使用IOUtils.toByteArray() 之类的东西将 InputStream 读入 byte[]

于 2013-04-07T01:52:28.903 回答