Does the Java 11 jar command support the classpath parameter?

2.6k Views Asked by At

I am currently studying for the OCP Java 11 certification and I am currently playing around with the basic JDK commands.

In the study guide there's a review question mentioning that the jar command also supports the -cp option (the classpath). Is this true? I am not aware of such thing, neither did I find the information in the official docs.

I know about the -C option, mentioning the path where the files to archive are located. Also, java and javac do accept -cp.

I am starting to believe it is an error in the study guide, but I wanted to double check first.

Is this valid?

jar -cf newJar.jar -cp /sample/dir .

This surely is:

jar -cf newJar.jar -C /sample/dir .

If the classpath parameter is indeed valid, what's the difference between -cp and -C? I am a bit confused.

Thanks.

1

There are 1 best solutions below

0
Nicolai Parlog On

As you point out, the docs don't mention the class path, so there's no reason to assume that -cp specifies it (leaving aside that I don't even know what jar could use the class path for). Or does it? Or can other options be combined to -cp? How can we be sure? By looking at the code!

There are two classes involved in parsing command line options: Main and GNUStyleCommandLineOptions. Let's start with the latter.

In GNUStyleOptions the method parseOptions parses the arguments:

static int parseOptions(Main jartool, String[] args) throws BadArgs {
    int count = 0;

    // [...]

    // [ iterate over each argument ]
    for (; count < args.length; count++) {
        // [...]
        // [ get the option's name ]
        String name = args[count];
        // [...]
        // [ look up the option ]
        Option option = getOption(name);
        // [...]
    }

    return count;
}

Note that this code contains no functionality to tear combined options apart and getOption doesn't either - it just looks up strings in a predefined array of recognized options. Since -p/--module-path is defined here, -c can't be combined with it to -cp.

Just for fun, let's check Main. There's parseArgs, which does understand combined flags and switches over each individual letter. This is where you'll find -c and also a -P, so -cP might work. I'll leave this as an exercise to the reader.