Combining Jar file with -classpath JAVA

2020-03-31 08:27发布

问题:

I have a question regarding compiling a class which has some dependent classes in a Jar file (MyJar.jar). By putting a directory tree in a -classpath option (ex: javac -cp MyJar MyClass.java ), will all the subdirectories be checked for classes or only the top level classes in the directory tree? Thanks in advance.

回答1:

will the directories specified with -cp be recursivly searched: No

when the classloader enters a directory specified in the classpath it starts using the package where the class is located as subdirectory. if no package is specified then the classloader will expect it under the immediate children (class files) of the directory.

It's a combination of -cp direcoties/jars and package name.

Lets say you have the following directory structur

+ Project
    sayhello.jar
    + dir
        + sub
            + com
                + test
                    SayHelloMain.java

Where the code of the class SayHelloMain.java is (note the package declaration)

package com.test;

import miscellaneous.so.SayHello;

public class SayHelloMain {
   public static void main(String[] args) {
       SayHello.sayIt();
   }
}

and the jar file sayhello.jar containing the class SayHello

this is how you'll have to compile the class SayHelloMain if the command line is opened in the same directory as the java source file

javac SayHelloMain.java -cp ..\..\..\..\sayhello.jar

or if the command line is opened in the the dierctory Project

javac dir\sub\com\test\SayHelloMain.java -cp sayhello.jar

Let's say u have opened a command line in the dierctory Project

This is how you can run the class SayHelloMain

java -classpath dir\sub;sayhello.jar com.test.SayHelloMain

the class name has to be fully qualified thus com.test.SayHelloMain

The command

java -classpath dir;sayhello.jar com.test.SayHelloMain

will no work since the direcotry dir is not recursively searched

the command

java -classpath dir;sayhello.jar sub.com.test.SayHelloMain

will also not work since there is no such package sub.com.test. A package is only that defined in the package declaration of a class



回答2:

If your directory tree represents packages, then all your classes will be loaded and usable.

For example, the following class:

package my.company.project;

public class MyClass {
    public static void main(String[] args) {}
}

Should be inside the folder my/company/project to be usable.