简体   繁体   中英

Creating Jar and loading classes in it

I need to create a jar and load classes inside jar using classLoader. I use following code to create folder structure inside jar.This works fine but when i try to load class from jar it throws exception 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
  {

  }
}

Classes to be jared are at location "D:\\myJar\\spring\\controller\\MyController.class" and " D:\\myJar\\spring\\service\\MyService.class".So jar is created as I want and also it contains folder structure(Mycontroller.class is inside jar at location \\myJar\\spring\\controller).But when i try to load it with following code I get exception

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();
    } 

} 

But if I create jar without package structure inside it.It works fine. I have checked all my paths and they are correct.Also location of class file inside Jar is correct. Please explain why am I getting ClassNotFound Exception .Also suggest if any change is required in createJar() or add() code.

You may need to add class-path on the go, the following link could be of help.

How do you change the CLASSPATH within Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM