Search code examples
javaeclipsebyteclassloaderbin

Loading class from bin folder


I would like to use .class file from bin folder in my code - convert it to bytes, but have no idea how to get to it. I have bin/example.class and I need to load it and check how many bytes does my class have.

I found something like:

public class MyClassLoader extends ClassLoader{ 

      public MyClassLoader(){ 
            super(MyClassLoader.class.getClassLoader()); 
      } 
}

But it doesn't seem to help, it must be some extremely easy way to do this. It looks really easy and whole internet try to push me into writing thousand lines of classLoader Code.

EDIT: My java file is compiled programatically and .class file is created programatically, so I can't just refer to it's name, it's also somewhere else in workspace.

Some hints?


Solution

  • Just add the bin folder to your class path!

    To get the number of bytes, get the resource URL, convert to a File object and query the size.

    Example:

    package test;
    
    import java.io.File;
    import java.net.URISyntaxException;
    import java.net.URL;
    
    public class Example {
    
        public static final String NAME = Example.class.getSimpleName() + ".class";
    
        public static void main(String[] args) throws URISyntaxException {
            URL url = Example.class.getResource(NAME);
            long size = new File(url.toURI().getPath()).length();
            System.out.printf("The size of file '%s' is %d bytes\n", NAME, size);
        }
    
    }
    

    Will output:

    The size of file 'Example.class' is 1461 bytes