Combining Jar file with -classpath JAVA

情到浓时终转凉″ 提交于 2019-12-01 13:50:21

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!