[英]Creating Jar and loading classes in it
我需要創建一個jar並使用classLoader在jar中加載類。 我使用以下代碼在jar中創建文件夾結構。這很好,但是當我嘗試從jar中加載類時會拋出ClassNotFound異常。
public void createJar() throws IOException
{
//FileOutputStream stream = new FileOutputStream("D:\\MyFolder\\apache-tomcat-6.0.32\\webapps\\SpringTest\\WEB-INF\\lib\\serviceJar.jar");
FileOutputStream stream = new FileOutputStream("D:/MyFolder/apache-tomcat-6.0.32/webapps/SpringTest/WEB-INF/lib/serviceJar.jar");
JarOutputStream target = new JarOutputStream(stream, new Manifest());
add(new File("D:/myJar"), target);
target.close();
stream.close();
}
private void add(File source, JarOutputStream target) throws IOException
{
byte buffer[] = new byte[10204];
try
{
if (source.isDirectory())
{
String name = source.getPath().replace("\\", "/");
if (!name.isEmpty())
{
if (!name.endsWith("/"))
name += "/";
JarEntry entry = new JarEntry(name);
entry.setTime(source.lastModified());
target.putNextEntry(entry);
target.closeEntry();
}
for (File nestedFile: source.listFiles())
add(nestedFile, target);
return;
}
JarEntry entry = new JarEntry(source.getPath().replace("\\", "/"));
// JarEntry entry = new JarEntry(source.getPath());
entry.setTime(source.lastModified());
target.putNextEntry(entry);
FileInputStream in = new FileInputStream(source);
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
break;
target.write(buffer, 0, nRead);
}
in.close();
target.closeEntry();
}
catch(Exception e){
}
finally
{
}
}
要震擊的類位於“ D:\\ myJar \\ spring \\ controller \\ MyController.class”和“ D:\\ myJar \\ spring \\ service \\ MyService.class”的位置。因此,可以根據需要創建jar並包含文件夾結構(Mycontroller.class在jar里面的\\ myJar \\ spring \\ controller內)。但是當我嘗試使用以下代碼加載它時,出現異常
public void loadJar() {
//File root = new File("D:\\MyFolder\\apache-tomcat-6.0.32\\webapps\\SpringTest\\WEB-INF\\lib\\serviceJar.jar");//
File root = new File("D:/MyFolder/apache-tomcat-6.0.32/webapps/SpringTest/WEB-INF/lib/serviceJar.jar");//
URLClassLoader classLoader;
try {
classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
Class<?> cls = Class.forName("myJar.spring.controller.MyController", true, classLoader);
Object instance = cls.newInstance(); // Should print constructor content
System.out.println(instance);
Method m =cls.getMethod("printThis", null);
m.invoke(instance, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
但是如果我創建的jar里面沒有包結構,那就可以了。 我已經檢查了所有路徑,它們都是正確的.Jar中類文件的位置也是正確的。 請解釋為什么我會收到ClassNotFound Exception。還建議在createJar()或add()代碼中是否需要任何更改。
您可能需要隨時添加類路徑,以下鏈接可能會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.