简体   繁体   中英

How to set java -classpath for two directories?

I am trying to get a little test working in Java. I have two directories root and root/lib . I have a root/lib/Test.java file and a root/Foo.java file. I can compile both with javac lib/Test.java and then javac -classpath lib Foo.java and get:

root/
 Foo.java
 Foo.class
 lib/
  Test.java
  Test.class

here is how they look like:

class Foo {
  static public void main(String[] argv) {
    System.out.println(Test.test());
  }
}

and

class Test {
  public static int test() {
    return 2;
  }
}

How do I run them so they work together without adding a import statement? I have tried java -classpath ".;lib" Foo but I just get java.lang.NoClassDefFoundError: Foo

Lala: jeena$ cd root
Lala:root jeena$ java -classpath ".;lib" Foo
Exception in thread "main" java.lang.NoClassDefFoundError: Foo
Caused by: java.lang.ClassNotFoundException: Foo
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)

This suggests that you're in the parent of root:

javac -classpath root/lib Foo.java

And this suggests that you're in root:

java -classpath ".;lib" Foo

Which directory are you actually working from? Perhaps absolute paths would be easier for you?

Also, what operating system? On Linux, for example, your path separator will be : instead of ; .

I'm not sure what the actual problem is - if you're on windows, and neither class uses a specific package name (ie, they're in the unnamed package, which you shouldn't use), then "java -classpath .;lib Foo" should be able to load and run Foo without a problem.

If they're not in the same package (which you haven't shown) then as long as Test is public, you can access the test() method by using "packageName.goes.here.Test.test()."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM