【发布时间】:2012-08-05 20:55:37
【问题描述】:
我正在构建一个应用程序,该应用程序必须在运行时加载当前类,并将其添加到我正在创建的另一个 .jar 中。我有一种将文件添加到 jar 中的方法。
private static void add(File source, JarOutputStream target,
Manifest manifest) throws IOException {
BufferedInputStream in = null;
try {
String name = source.getName();
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
in = new BufferedInputStream(new FileInputStream(source));
byte[] buffer = new byte[1024];
while (true) {
int count = in.read(buffer);
if (count == -1)
break;
target.write(buffer, 0, count);
}
target.closeEntry();
} finally {
if (in != null)
in.close();
}
}
我的问题是:我似乎不知道如何在运行时将当前类添加到文件中。我试过这个:
File classFile= new File(getClass().getResource("MyClass.class").getPath());
但我得到一个空指针异常。任何帮助将不胜感激。
【问题讨论】:
-
这是主要课程吗?它是由引导类加载器加载的吗?这个类所在的包层次结构是什么?
-
是的,这是主要课程。它只是坐在默认包中。
-
您是否尝试在 MyClass.class 之前添加斜杠:getResource("/MyClass.class") ?