crow
crow

Reputation: 1

How to programatically add variables to the Shell from which some code was invoked?

with jshell, is there a way to create variables in the scope of the interpreter? I have something like

Map<String,Object> vars = loadVarsFromSomething();

and I would like to be able to do something like

for ( Map.Entry<String,Object> key : vars )
{
  scope.put( key.getKey(), key.getValue() );
}

Is that possible?

Note here that the "scope" I am referring to is the actual scope of the Shell object that is being used by jshell interpreter.. I need to get a reference to the shell that the code is being invoked from so that I can create variables that look as if they were assigned by the user/caller ..

Upvotes: 4

Views: 360

Answers (2)

Per Huss
Per Huss

Reputation: 5095

No, I don't believe it's possible to do what you are asking for. I'm not sure exactly what your use case is, but perhaps you can use the following snippet for ideas:

jshell> /vars 
|    HashMap<String, Object> vars = {bar=2, foo=1}

jshell> try (PrintStream out = new PrintStream(new FileOutputStream("tmp.jsh"))) {
...>     vars.forEach((k, v) -> out.printf("Object %s = vars.get(\"%s\")\n", k, k));
...> }

jshell> /open tmp.jsh

jshell> /vars 
|    HashMap<String, Object> vars = {bar=2, foo=1} 
|    Object bar = 2 
|    Object foo = 1

jshell>

Upvotes: 1

Naman
Naman

Reputation: 31868

To load variables from an input file you can make use of the Jshell script itself.

Assuming the Jshell script named some.jsh needs to supply two variables such that one of them is a String and another is a primitive integer.

// Random stuff initially
{
  System.out.println("One Jshell Script");
}
// Variables to be supplied when jshell loads.
int x = 10;
String y = "Cool";

On executing the above script using:

jshell some.jsh 

You can thereafter access these variables with their identifiers as follows:-

enter image description here

Undoubtedly, you can make use of more complex data structure(in your case Map<String,Object> vars) as well as you store information in the script.

Upvotes: 6

Related Questions