11/*
2- * Copyright (c) 2013, 2021 , Oracle and/or its affiliates. All rights reserved.
2+ * Copyright (c) 2013, 2023 , Oracle and/or its affiliates. All rights reserved.
33 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44 *
55 * This code is free software; you can redistribute it and/or modify it
3232import java .util .Arrays ;
3333import java .util .List ;
3434
35- import javax .tools .ForwardingJavaFileManager ;
3635import javax .tools .FileObject ;
36+ import javax .tools .ForwardingJavaFileManager ;
3737import javax .tools .JavaCompiler ;
3838import javax .tools .JavaCompiler .CompilationTask ;
3939import javax .tools .JavaFileManager ;
@@ -168,25 +168,12 @@ public boolean hasLocation(Location location) {
168168 * @param className The name of the class
169169 * @param sourceCode The source code for the class with name {@code className}
170170 * @param options additional command line options
171- * @throws RuntimeException if the compilation did not succeed
171+ * @throws RuntimeException if the compilation did not succeed or if closing
172+ * the {@code JavaFileManager} used for the compilation did not succeed
172173 * @return The resulting byte code from the compilation
173174 */
174175 public static byte [] compile (String className , CharSequence sourceCode , String ... options ) {
175176 MemoryJavaFileObject file = new MemoryJavaFileObject (className , sourceCode );
176- CompilationTask task = getCompilationTask (file , options );
177-
178- if (!task .call ()) {
179- throw new RuntimeException ("Could not compile " + className + " with source code " + sourceCode );
180- }
181-
182- return file .getByteCode ();
183- }
184-
185- private static JavaCompiler getCompiler () {
186- return ToolProvider .getSystemJavaCompiler ();
187- }
188-
189- private static CompilationTask getCompilationTask (MemoryJavaFileObject file , String ... options ) {
190177 List <String > opts = new ArrayList <>();
191178 String moduleOverride = null ;
192179 for (String opt : options ) {
@@ -196,6 +183,19 @@ private static CompilationTask getCompilationTask(MemoryJavaFileObject file, Str
196183 opts .add (opt );
197184 }
198185 }
199- return getCompiler ().getTask (null , new FileManagerWrapper (file , moduleOverride ), null , opts , null , Arrays .asList (file ));
186+ try (JavaFileManager fileManager = new FileManagerWrapper (file , moduleOverride )) {
187+ CompilationTask task = getCompiler ().getTask (null , fileManager , null , opts , null , Arrays .asList (file ));
188+ if (!task .call ()) {
189+ throw new RuntimeException ("Could not compile " + className + " with source code " + sourceCode );
190+ }
191+
192+ return file .getByteCode ();
193+ } catch (IOException ioe ) {
194+ throw new RuntimeException (ioe );
195+ }
196+ }
197+
198+ private static JavaCompiler getCompiler () {
199+ return ToolProvider .getSystemJavaCompiler ();
200200 }
201201}
0 commit comments