I have implemented a method that generates Java code:
public static String generate() { ... }
It returns Java code as a String
, i.e. I might get
"public class X { public static String x() { return \"x\"; } }"
as a value returned by generate
. Now, I am in a JShell Tool (JEP-222) session, and I can call generate
, but I fail to load the result of generate
into JShell itself.
Ideally I'd like to achieve the following
jshell> eval(generate());
| created class X
jshell> X.x();
$2 ==> "x"
In the above (hypothetical) JShell sesssion, eval
is the function that I am looking for.
Possible solutions I already tried:
- I know that this would be possible by calling
JShell#eval
but I failed to obtain theJShell
object that represents the currently running JShell. - It might be that there is some facility in JShell that allows lifting a
String
to a Snippet. I couldn't find something like that, but if there is, it might be helpful. - I know that I can
/open
a file, so it might be possible to write theString
to a file and then open/load it. However this is a two-step process, and I would prefer to have a solution that is simpler.