Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the Java 9 jshell be used to run code in another JVM?

Java 9 has a read-eval-print loop for Java, called jshell. I've seen it work in it's basic mode, from the command line. Can it also be used in a remote process? In other words, can I connect to another Java process and enter code snippets to run within that runtime? This would be a nice way to change configuration state in an app server without having to write an admin tool with a UI.

like image 568
Rob N Avatar asked Jul 05 '17 15:07

Rob N


People also ask

What is the use of JShell in Java 9?

The Java Shell tool (JShell) is an interactive tool for learning the Java programming language and prototyping Java code. JShell is a Read-Evaluate-Print Loop (REPL), which evaluates declarations, statements, and expressions as they are entered and immediately shows the results. The tool is run from the command line.

Is JShell introduced in Java 9?

JShell is a Java read-eval-print loop which was first introduced in the JDK 9.

How do I run a Java file in JShell?

To load a file into the JShell tool, we can use the "/open" command. The "/open" command has loaded the "Test. java" file into a session. The "/vars" command can be used to load the variables into a session and "/methods" command can be used to load the methods into a session.

Is JShell an interpreter?

What is JShell? One of the new features in Java 9 is JShell which is a Read-Eval-Print-Loop (REPL) interpreter. A REPL is an interactive shell that allows execution of single statements without the need to compile a complete program.


1 Answers

Attaching JShell is a project that implements an extension to JShell for exactly this. It uses the Java Agent for communication with the target JVM.

I have not used it so I cannot say how well it works.

Observations after a quick inspection

  • The read-me file looks professional.
  • The code looks small and pretty simple, as if it hasn't been under development for a long time.
  • There are no tickets in the bug tracker, which indicates that it hasn't been used much.

Example from the project read-me

  • Start the target JVM with -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=XXXhostname:XXXport (update XXXhostname and XXXport as appropriate) and call new uk.org.cinquin.attaching_jshell.ExistingVMRemoteExecutionControl() from that JVM prior to using JShell.

  • call JShell as follows: java -cp lib/attaching_jshell.jar jdk.internal.jshell.tool.JShellToolProvider --execution "attachToExistingVM:hostname(XXXhostname),port(XXXport)" using the same values of XXXhostname and XXXport as above

  • Run code in the remote JVM like this:

    import uk.org.cinquin.attaching_jshell.ExistingVMRemoteExecutionControl;
    String s = ExistingVMRemoteExecutionControl.theGoodsForTesting
    
like image 74
Lii Avatar answered Oct 25 '22 09:10

Lii