考虑以下 java 程序:
import computer_package.Computer;
import com.sun.jna.Library;
public class HelloWorld {
public static void main(String[] args) {
Computer computer = new Computer();
System.out.println("Hello, World");
}
}
和以下目录结构:
Rebs-MacBook-Pro:jalint2 rebcabin$ find computer_package/
computer_package/
computer_package//Computer.class
computer_package//Computer.java
其中Computer.java
如下:
package computer_package;
public class Computer {
public Computer() {
System.out.println("Constructor of Computer class.");
}
public void computer_method() {
System.out.println("Power gone! Shut down your PC soon...");
}
}
和另一个只有jar
文件的目录:
Rebs-MacBook-Pro:jalint2 rebcabin$ find com
com
com/sun
com/sun/jna
com/sun/jna/jna-4.0.0.jar
com/sun/jna/jna-platform-4.0.0.jar
如果我只注释掉import com.sun.jna;
原始HelloWorld.java
文件中的行,那么一切正常
Rebs-MacBook-Pro:jalint2 rebcabin$ javac -g HelloWorld.java
Rebs-MacBook-Pro:jalint2 rebcabin$ java HelloWorld
Constructor of Computer class.
Hello, World
Javac 和 java 能够在./computer_package/Computer.class
没有任何进一步提示或注释或类路径黑客攻击的情况下找到类文件。
现在,如果我恢复该import com.sun.jna;
行并仅注释掉import computer_package.Computer;
构造 a 的行和行new Computer
,并像这样编译:
Rebs-MacBook-Pro:jalint2 rebcabin$ javac -g -cp "./com/sun/jna/jna-4.0.0.jar" HelloWorld.java
甚至像这样:
Rebs-MacBook-Pro:jalint2 rebcabin$ make
javac -g -cp "./com/sun/jna/jna-4.0.0.jar:./computer_package" HelloWorld.java
那么一切都很好:
Rebs-MacBook-Pro:jalint2 rebcabin$ java HelloWorld
Hello, World
At least, the import com.sun.jna;
line didn't throw a compiler error -- admittedly, I am not yet using the jna library; I'm just trying to build up to that momentous achievement in baby steps.
So if I now cautiously uncomment the import computer_package;
line and the line that constructs an instance of Computer
, yielding the HelloWorld.java
file at the top of this question that tries to use both my Computer
class and jna, all hell breaks loose; the previously acceptable Computer
class is now inaccessible:
Rebs-MacBook-Pro:jalint2 rebcabin$ make
javac -g -cp "./com/sun/jna/jna-4.0.0.jar:./computer_package" HelloWorld.java
HelloWorld.java:20: error: package computer_package does not exist
import computer_package.Computer;
^
HelloWorld.java:25: error: cannot access Computer
Computer computer = new Computer();
^
bad class file: ./computer_package/Computer.class
class file contains wrong class: computer_package.Computer
Please remove or make sure it appears in the correct subdirectory of the classpath.
2 errors
make: *** [HelloWorld.class] Error 1
I know this is elementary; I am not a java expert and I admit I am trying to guess my way around the classpath nightmare world; I am using just emacs and bash, avoiding the IDEs that add even more layers of opaque abstraction.