简体   繁体   中英

java jar getClass().getClassLoader().getResourceAsStream return nullpointerexception

Image: This is my Project directory

In MainRun class, i have the following code:

package bin;
public class MainRun{
   public static void main(String[] args){

    compileCode("Square.java");

    int length = 0;
    MCAMClassLoader classLoader = new MCAMClassLoader();
    Class<?> c= classLoader.findClass(bin.Square);

    try{
        Shape myClassObject = (Shape)c.newInstance();
        Method method = c.getMethod(getLength);
        Object result = method.invoke(myClassObject);
        length = (int)result;
    }
    catch(Exception e){
        e.printStackTrace();
    }
    System.out.println(length);
  }

  public void compileCode(String _filename){
     String[] args = new String[] {"-d", "C:\Users\Tan\Downloads\MCAM", "C:\Users\Tan\Downloads\MCAM\src\"+_filename};
    com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
    javac.compile(args);
  }
}

In my custom ClassLoader, i have the following code:

package bin;
public class MCAMClassLoader extends ClassLoader{
  @Override
  public Class<?> findClass(String name) 
  {
      byte[] bt = loadClassData(name);
      return defineClass(name, bt, 0, bt.length);
  }

  private byte[] loadClassData(String className) {

    InputStream is =  this.getClass().getClassLoader().getResourceAsStream(className.replace(".", "/")+".class"); //it will end up with bin/Square.class
    ByteArrayOutputStream byteSt = new ByteArrayOutputStream();

    int len =0;
    try 
    {
        while((len=is.read())!=-1)
        {
            byteSt.write(len);
        }
    } catch (IOException e) {
         e.printStackTrace();
    }

    return byteSt.toByteArray();
  }
}

And i have my Square class added and compiled on run time. Square.class will be located in bin folder.

package bin;
public class Square extends Shape{

  public Square(){
    length = 8;
  }

  public int getLength(){
    return length;
  }
}

These codes work perfectly fine when it was executed by .bat on console. Only when i build those files into a jar file and run it, I will get the error on the console: NullPointerException which fall on the line "while((len=is.read())!=-1)".

Note: in my MANIFEST.MF

Manifest-Version: 1.0
Main-Class: bin.MainRun
Class-Path: .\lib\xmlbeans-2.6.0.jar .\lib\tools.jar

Why? Am I using the ClassLoader incorrectly? Something else? Please advise and thanks in advance

There are (often) no directories inside jar files. Therefore it will return null.

If you want to get the file you could get that resource directly:

InputStream fileInputStream = getClass().getResourceAsStream(File.pathSeparator+className+".class");

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