开发者

How to set java -classpath for two directories?

开发者 https://www.devze.com 2023-02-28 09:54 出处:网络
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 t

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.开发者_StackOverflow社区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 (i.e., 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()."

0

精彩评论

暂无评论...
验证码 换一张
取 消