Thibstars
Thibstars

Reputation: 1083

Is there a way to remove imports in JShell?

I'm discovering JShell and I discovered the imports added in by default:

jshell> /imports
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*

After doing that I added my own import using the following command:

import java.lang.Math

Is there a way to remove the latter import without killing the active session/restarting?

I've tried to issue the /edit command, remove the import, click accept and click exit, but that didn't do the trick.

As stated in the comments, /reset removes the import, but it also removes anything else previously input in the session. Is there a specific way to ONLY remove the import statement?

Upvotes: 4

Views: 622

Answers (2)

steffen
steffen

Reputation: 16948

For those who are searching for a way to auto-import common libraries:

$ jshell JAVASE

This automatically imports about 200 Java SE packages. But there are duplicate class names: List<Duration> is ambigous (java.awt.List and javax.xml.datatype.Duration).

jshell> List<Duration> list;
|  Error:
|  reference to List is ambiguous
|    both class java.awt.List in java.awt and interface java.util.List in java.util match
|  List<Duration> list;
|  ^--^
|  Error:
|  reference to Duration is ambiguous
|    both class javax.xml.datatype.Duration in javax.xml.datatype and class java.time.Duration in java.time match
|  List<Duration> list;
|       ^------^

This can be resolved with a startup script:

echo "/imports" | jshell JAVASE - | awk '{printf("%s %s;\n", $1, $2)}' > jshell-imports-tmp
remove_imports=(".awt." " org." " javax.")
printf '%s\n' "${remove_imports[@]}" | grep -Fvf - jshell-imports-tmp > jshell-imports
echo "/set start -retain jshell-imports" | jshell -
rm jshell-import*

Check that it works

jshell> List<Duration> list;
list ==> null

Upvotes: 0

Thibstars
Thibstars

Reputation: 1083

After some searching, I managed to find a solution. It's a combination of /list (to know which line to remove) and /drop.

/drop [name[ name...]|id[ id...]]

Drops a snippet, making it inactive. Provide either the name or the ID of an import, class, method, or variable. For more than one snippet, separate the names and IDs with a space. Use the /list command to see the IDs of code snippets.

jshell> import java.lang.Math

jshell> /list

   1 : import java.lang.Math;

jshell> /drop 1

jshell> /imports
|    import java.io.*
|    import java.math.*
|    import java.net.*
|    import java.nio.file.*
|    import java.util.*
|    import java.util.concurrent.*
|    import java.util.function.*
|    import java.util.prefs.*
|    import java.util.regex.*
|    import java.util.stream.*

Upvotes: 5

Related Questions