26
26
import org .dflib .jjava .JavaKernel ;
27
27
import jdk .jshell .*;
28
28
29
+ import java .lang .reflect .InvocationTargetException ;
29
30
import java .lang .reflect .Method ;
30
31
import java .util .List ;
31
32
import java .util .regex .Matcher ;
@@ -46,6 +47,7 @@ public class CodeEvaluator {
46
47
throw new RuntimeException ("Unable to access jdk.jshell.Snippet.classFullName() method." , e );
47
48
}
48
49
}
50
+ private static final String INDENTATION = " " ;
49
51
50
52
private final JShell shell ;
51
53
private final JJavaExecutionControlProvider executionControlProvider ;
@@ -55,7 +57,6 @@ public class CodeEvaluator {
55
57
private boolean isInitialized = false ;
56
58
private final List <String > startupScripts ;
57
59
58
- private final String indentation = " " ;
59
60
60
61
public CodeEvaluator (JShell shell , JJavaExecutionControlProvider executionControlProvider , String executionControlID , List <String > startupScripts ) {
61
62
this .shell = shell ;
@@ -172,14 +173,26 @@ public Object eval(String code) throws Exception {
172
173
/**
173
174
* Try to clean up information linked to a code snippet and the snippet itself
174
175
*/
175
- private void dropSnippet (Snippet snippet )
176
- throws Exception {
176
+ private void dropSnippet (Snippet snippet ) throws Exception {
177
177
JJavaExecutionControl executionControl =
178
178
this .executionControlProvider .getRegisteredControlByID (this .executionControlID );
179
179
this .shell .drop (snippet );
180
180
// snippet.classFullName() returns name of a wrapper class created for a snippet
181
- String className = SNIPPET_CLASS_NAME_METHOD .invoke (snippet ).toString ();
182
- executionControl .unloadClass (className );
181
+ String className = snippetClassName (snippet );
182
+ // check that this class is not used by other snippets
183
+ if (this .shell .snippets ()
184
+ .map (this ::snippetClassName )
185
+ .noneMatch (className ::equals )) {
186
+ executionControl .unloadClass (className );
187
+ }
188
+ }
189
+
190
+ private String snippetClassName (Snippet snippet ) {
191
+ try {
192
+ return SNIPPET_CLASS_NAME_METHOD .invoke (snippet ).toString ();
193
+ } catch (IllegalAccessException | InvocationTargetException e ) {
194
+ throw new RuntimeException (e );
195
+ }
183
196
}
184
197
185
198
private String computeIndentation (String partialStatement ) {
@@ -222,7 +235,7 @@ private String computeIndentation(String partialStatement) {
222
235
}
223
236
224
237
return newlyOpenedBraces > 0 || newlyOpenedParens > 0
225
- ? currentIndentation + this . indentation
238
+ ? currentIndentation + INDENTATION
226
239
: currentIndentation ;
227
240
}
228
241
0 commit comments