Classpath is a tricky thing to do in Java, and I talked about what classpath is in my previous article.

1: The classpath is the SRC folder in the project structure before packaging.

2: After maven is packaged, you will see a target folder in idea, where classes is classpath.

3: When you actually run a JAR package, if you want to get resources inside the JAR, it is best to use class.getResource to locate the anchor points.

4: When you run a.class file in Java, the current directory is also classpath.

Classpath looks simple, but actually it’s not easy to get deep into it. To understand a classpath, run the.class file with a Java command.

Sometimes we need to directly use the Java command provided by the JDK to execute the class file to get the software running, especially many beginners, but often find the following prompt:

“Error: Main class cannot be found or loaded”

The reason is simple. We missed two details.

1. By default, the Java directive looks for the address of the class file in the directory specified in the CLASSPATH environment variable.

2. We ignored the impact of package. The first problem is easy to solve:

We add “. “directly to the CLASSPATH environment variable. Can. “.” Search the current directory

The second question is analyzed below:

The former has no package name, while the latter has a package name. Executing javac directly generates a. Class file in the directory, runs it directly with Java commands (note: no. Class suffix), outputs and hello World.

The latter will report an error doing so. According to Java, the full name of a class should be the package name + the class name. Therefore, the source files should be stored in the path defined by package. The latter must create a org/will/app/main folder and put the class into it to compile.

Here we go! Are you /… at this time /… /org/will/app/main Java NewsManager still fails. Because, in fact, you execute the path: /… /… / org/will/app/main/org/will/app/main/NewsManager, because the class contains the package name, so repeated. You should exit the org folder and execute Java /app/main/NewsManager. Successfully output Hello World.

Of course, you can also specify the classpath at run time without having to roll back the org folder. Such as

java classpath /... /... /app/main/NewsManagerCopy the code

This also works, printing Hello World.

Refer to the article, https://www.cnblogs.com/wangxiaoha/p/6293340.html