Combining Jar file with -classpath JAVA

前端 未结 2 929
情深已故
情深已故 2021-01-17 03:01

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

相关标签:
2条回答
  • 2021-01-17 03:26

    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

    0 讨论(0)
  • 2021-01-17 03:40

    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.

    0 讨论(0)
提交回复
热议问题