0

I compile a class successfully like this:

zookeeper@zookeeper-virtual-machine:~/zookeeper-3.4.5$ javac -cp "zookeeper-3.4.5.jar" org/zookeeper/Worker.java

But when I then try to run it Java's class loader can't find the class:

zookeeper@zookeeper-virtual-machine:~/zookeeper-3.4.5$ java -cp "zookeeper-3.4.5.jar" org.zookeeper.Worker
Exception in thread "main" java.lang.NoClassDefFoundError: org/zookeeper/Worker
Caused by: java.lang.ClassNotFoundException: org.zookeeper.Worker
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: org.zookeeper.Worker. Program will exit.

Here are the relevant parts of Worker.java

package org.zookeeper;
...

class Worker implements Watcher {

...

    public static void main(String[] args) throws Exception {
        Worker worker = new Worker(args[0], args[1],args[2]);
        worker.processRequest();
    }

Why can't the class loader load the class?

2
  • Does zookeeper-3.4.5.jar actually contain the class? Commented Nov 13, 2013 at 21:47
  • @Reimeus no. I wrote the worker class and store/compile it in org/zookeeper. But the Worker class depends on things in zookeeper-3.4.5.jar Commented Nov 13, 2013 at 21:47

2 Answers 2

2

When the -cp flag is specified, the current directory is not automatically used in the classpath so needs to be added explicitly:

java -cp zookeeper-3.4.5.jar:. org.zookeeper.Worker
Sign up to request clarification or add additional context in comments.

Comments

0

Why quote the jar anyway?

In any case, you still need your classes on the classpath, e.g.,

java -cp .:zookeeper-3.4.5.jar org.zookeeper.Worker

5 Comments

I quote the jar because worker depends on classes in the jar to run and java needs to find them. Correct?
@abe3 That's why you need the jar, I asked why you quoted the jar.
I guess I am in the habit of putting class paths in quotes. I take it that is not nevessary?
@abe3 Rarely; if a path has a space in it then you can use quotes or just escape the space. There aren't any other dependencies required for zookeeper, though? Classpath management is often (usually) better handled by stuff like Maven etc.
there are -- but I added them into the classpath after resolving this issue. Tx for tips.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.