Search code examples
javajava-compiler-api

Using Java Compiler API, what classes were created?


Because a single Java file can compile into any number of class files, is there some way from the compiler API to find out which class files were generated? It's outputting to a directory that may have other files in it, so I can't just look at that.


Solution

  • I figured out something that appears to work. The *FileManager has callbacks to get the locations for things, including things for output. You can wrap it using the ForwardingJavaFileManager, override, and store the values from the calls.

    final List<String> classFiles = new ArrayList<>();
    StandardJavaFileManager inner = compiler.getStandardFileManager(null, null, null);
    JavaFileManager fileManager = new ForwardingJavaFileManager(inner) {
        @Override
        public JavaFileObject getJavaFileForOutput(Location location, String className,
                    JavaFileObject.Kind kind, FileObject sibling) throws IOException {
            JavaFileObject o = super.getJavaFileForOutput(location, className, kind, sibling);
            classFiles.add(o.getName());
            return o;
        }
    };