我有一个 Java 类,它的 main 方法需要参数。如果我在没有参数的情况下运行该类,我会收到这样的错误,这意味着 Java 找到了该类,运行它,并生成一个运行时 ArrayIndexOutOfBoundsException。
zookeeper@zookeeper-virtual-machine:~/zookeeper-3.4.5$ java -cp .:zookeeper-3.4.5.jar org.zookeeper.LsGroup
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at org.zookeeper.LsGroup.main(LsGroup.java:50)
但是,当我尝试使用必需的命令行参数 ( zookeeper@zookeeper-virtual-machine:~/zookeeper-3.4.5$ java -cp .:zookeeper-3.4.5.jar org.zookeeper.LsGroup Test
) 执行相同的语句时,我得到一个找不到类的错误:
zookeeper@zookeeper-virtual-machine:~/zookeeper-3.4.5$ java -cp .:zookeeper-3.4.5.jar org.zookeeper.LsGroup Test
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.apache.zookeeper.ZooKeeper.<clinit>(ZooKeeper.java:94)
at org.zookeeper.LsGroup.connect(LsGroup.java:19)
at org.zookeeper.LsGroup.main(LsGroup.java:50)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
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)
... 3 more
zookeeper@zookeeper-virtual-machine:~/zookeeper-3.4.5$
我今天早上早些时候遇到了类似的问题,但该线程上的特定问题已解决。 为什么java找不到我的类?
为什么我在传递命令行参数时会收到类未找到错误?我怎样才能解决这个问题?
这是java代码:
package org.zookeeper;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class LsGroup implements Watcher {
private static final int SESSION_TIMEOUT = 5000;
private ZooKeeper zk;
private CountDownLatch connectedSignal = new CountDownLatch(1);
public void connect(String hosts) throws IOException, InterruptedException {
zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
connectedSignal.await();
}
@Override
public void process(WatchedEvent event) { // Watcher interface
if (event.getState() == KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
public void ls(String groupName) throws KeeperException, InterruptedException {
String path = "/" + groupName;
try {
List<String> children = zk.getChildren(path, false);
for (String child : children) {
System.out.println(path+"/"+child);
System.out.println(zk.getChildren(path +"/"+ child, false));
}
} catch (KeeperException.NoNodeException e) {
System.out.printf("Group %s does not exist\n", groupName);
System.exit(1);
}
}
public void close() throws InterruptedException {
zk.close();
}
public static void main(String[] args) throws Exception {
LsGroup lsGroup = new LsGroup();
lsGroup.connect(args[0]);
lsGroup.ls(args[1]);
lsGroup.close();
}
}