Search code examples
javalinuxtomcatcompiler-errorsjava-compiler-api

Java Compiler API (Linux): cannot find symbol for custom classes


I have a rather specific problem with the Java Compiler API. For my Usecase I have to generate, compile and load a java-class at runtime in my Web-Application (using Tomcat).

In order to do that, I create a .java-File on my disk, compile it, using the Compiler API and and then load it via a custom classloader. All of that works just fine on windows, but once I try running it on the Ubuntu-system it is supposed to be installed on, the compiler cannot find any custom classes that are referenced in the class. (Both systems use java 8 and the same version of Tomcat.)

The file is created correctly and stored in a subdirectory of the webapplication. ('catalina.home/webapps/projectname/resources/') All the .class-files of my application are stored in 'catalina.home/webapps/projectname/WEB-INF/classes/'. This directory is later added to the classpath of the compiler:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
File classesFolder = new File(TestFile.class.getProtectionDomain().getCodeSource().getLocation().getFile());        
List<String> optionList = new ArrayList<String>();
//Adding the classpath to the OptionList
optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path") + ";" +  Settings.projectPath + "WEB-INF/classes/;" + classesFolder.getAbsolutePath() )); 
CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, files); //a task is initialized with the values previously specified and saved
task.call();

The assigned values for the classpath do point to the directory, where the .class-Files are. But for some reason I keep getting

cannot find symbol
symbol:   class *nameOfReferencedClass*
location: class testfiles.TestFile

for every single class that is referenced... (I did not forget to import things, the packages are declared correctly and there are no syntax errors or misspelled names. I double checked that and as I mentioned, it works fine if the application is running on windows). I even tried to save the src-File inside of /WEB-INF/classes/, where the referenced classes reside and compile it there, but that didn't help either.

I do not have any idea, why the compiler would not find these classes and what could be different for linux. Could it be related to the file permissions or to the way Tomcat is configured (e.g. if it is run as root instead of a user)?


Solution

  • Try using a colon instead of a semi-colon as the classpath separator. On windows, the semi-colon is correct, but on *nix a semi-colon actually ends a shell command, so a colon is used instead.

    See the comment by @Slaw for a platform independent way to do this.