Search code examples
javapackageprivatejava-9jshell

Importing Package-Private Classes to JShell


I was playing around with JShell after the Java 9 release, and I tried importing a package I made. As the entire application I'm coding it for will be contained in that package, every class but one (which I haven't coded yet) is package-private. My classpath is correct, but I still can't use any of the types declared in the package in JShell (it throws a "cannot find symbol" error). Do I need to make them public for them to be accessible, or is there some way I can test package-private classes? Here's the exact code I tried.

My current directory is

C:\Users\Sylvaenn\OneDrive\Documents\Programs\Java\src

My class path is

C:\Users\Sylvaenn\OneDrive\Documents\Programs\Java\cls

and the package directory (for the bytecode) is

C:\Users\Sylvaenn\OneDrive\Documents\Programs\Java\cls\collatz

CollatzSequence is a package-private class contained in collatz.

PS C:\Users\Sylvaenn> cd OneDrive\Documents\Programs\Java\src
PS C:\Users\Sylvaenn\OneDrive\Documents\Programs\Java\src> jshell
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro

jshell> import collatz.*;

jshell> CollatzSequence seq = new CollatzSequence(BigInteger.ONE);
|  Error:
|  cannot find symbol
|    symbol:   class CollatzSequence
|  CollatzSequence seq = new CollatzSequence(BigInteger.ONE);
|  ^-------------^
|  Error:
|  cannot find symbol
|    symbol:   class CollatzSequence
|  CollatzSequence seq = new CollatzSequence(BigInteger.ONE);
|                            ^-------------^

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.*
|    import collatz.*

jshell>

Solution

  • As far as i know (correct me if i am wrong), you cannot create a Class in a specific package using JShell (classes created within JShell are always in the default package).

    That being said, you cannot access your package-private classes from within JShell. This is "normal" Java behaviour.