Home » Java » Crazy Idea: How to make JavaCompiler.CompilationTask use custom ClassLoader or use .class files for missin .java files?

Crazy Idea: How to make JavaCompiler.CompilationTask use custom ClassLoader or use .class files for missin .java files?

Posted by: admin July 12, 2018 Leave a comment

Questions:

More spicific: I havewritten my own ClassLoader, that loads

  1. .jar files from global library path
  2. .jar files from project specific path
  3. compiles .java files in project specific path
  4. loads all .class files in project specific path

So far, this separates my project instances, loads everything fine from all (sub)directories, works for (1) all libraries and (2) sub-libraries, (3) can compile all .java files, (4) can load .class files, and I also can re-instanciate classes that are already loaded, because my ClassLoader manages sub-ClassLoaders to allow this.

Now, what I want to improve is that at (3) when I call the compiler, I do not wanna re-compile every .java file in the directory, but only those, where the corresponding .class file does not exist or has the wrong timestamp.

So I only pass those .java files, that need re-compiling, not all, with the consequence, that the compiler cannot find all needed classes (inside those .java files that I didnt pass him to compile). Rather, the compiler shall get its missing compilation information (.class files instad of .java files) from my ClassLoader, that has already loaded those .class files.

To realize that, I have implemented my own FileManager, that I pass to JavaCompiler.getTask(). Within that custom FileManager, I return my ClassLoader in FileManager.getClassLoader().

Should look like this:

  1. .jar files from global library path
  2. .jar files from project specific path
  3. compiles only some .java files in project specific path, loading missing class definitions from .class files (loaded by my specific ClassLoader)
  4. loads all .class files in project specific path

But when the JavaCompiler.CompilationTask runs, it never accesses my ClassLoader’s .loadClass() or .findClass() methods, thus does not find the necessary .class files, thus ‘throws’ me a compilation error. (i.e. I get the diagnostics, and transform them into an Exception)

So, my actual question is:

  • Is my concept broken?
  • Is it possible at all? Or is the compiler unable to use .class files instead of .java files?
  • Is there any mean trick to it?
Answers: