Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

Java "Could not find or load main class" despite specifying class path?

I have a simplified Java project with the following structure:

.
└── hello
    ├── HelloWorld.class
    └── HelloWorld.java

where HelloWorld.java reads

package hello;

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

In the project directory, if I run java hello.HelloWorld the program runs:

~/D/S/my-java-project> java hello.HelloWorld
Hello World!

Reading through https://www.baeldung.com/java-could-not-find-load-main-class, I would expect that if I go to the hello directory and run the same command but specify the class path as the parent directory, it would work; however, I get a Could not find or load main class error:

~/D/S/my-java-project> cd hello
~/D/S/m/hello> java hello.HelloWorld -cp ..
Error: Could not find or load main class hello.HelloWorld
Caused by: java.lang.ClassNotFoundException: hello.HelloWorld

Any idea why this doesn't work?

question from:https://stackoverflow.com/questions/65845921/java-could-not-find-or-load-main-class-despite-specifying-class-path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The -cp option must precede the name of the class, otherwise it would be treated as an argument to the program:

java -cp .. hello.HelloWorld

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...