我是一位经验丰富的程序员,但多年来没有使用过 Java(主要是 C#),并且过去使用过 IDE。我正在尝试从 Mac 上的命令行编译一些代码,但无法让我的测试文件找到我的源代码。我假设问题出在包、文件结构、类路径和导入语句的空间中的某个地方 - 但我已经花了几个小时(包括在 Stack Overflow 上寻找),但我仍然陷入困境。
这是我所拥有的:
Directory structure:
ProjectName
|
--src
|
--SourceClass
--test
|
--SourceClassTest
--external
|
--testng-6.8.7.jar
我的 SourceClass 看起来像这样:
package ProjectName;
public class SourceClass<T>{
}
非常简单。显然,还会有更多 - 但我想在实际编码之前首先确保所有这些设置都是正确的。
我的测试类如下所示:
package ProjectName;
import java.util.*;
import org.testng.Assert;
import org.testng.annotations.*;
public class SourceClassTest{
@Test
private void createEmptySourceClass(){
SourceClass<Object> sourceClass = new SourceClass<Object>();
Assert.assertTrue(sourceClass.isEmtpy());
}
}
从“ProjectName”目录运行“javac src/*.java”,sourceClass 编译没有问题。我希望看到此失败并出现“SourceClass 没有 isEmpty() 方法”的错误,但我从“ProjectName”目录中像这样运行 javac:
javac test/*.java -classpath external/testng-6.8.7.jar
并得到这个异常:
test/SourceClassTest.java:12: error: cannot find symbol
SourceClass<Object> tree = new SourceClass<Object>();
^
symbol: class SourceClass
location: class SourceClassTest
test/SourceClassTest.java:12: error: cannot find symbol
SourceClass<Object> sourceClass = new SourceClass<Object>();
^
symbol: class SourceClass
location: class SourceClassTest
2 errors
我已经尝试了很多事情 - 添加导入语句,向 javac 命令添加源路径,将 sourceClass 编译为 jar 并将其放入 bin 目录中,然后将其添加到类路径中,但我不能进行测试以查找 SourceClass 符号。
知道我在这里缺少什么吗?
最佳答案
如果您编译到单独的目标目录中,它就可以工作。例如,
mkdir target
javac -d target/ src/*.java
javac -classpath target/ test/*.java
当您执行javac src/*.java
时,它将在src
目录本身中创建.class
文件。默认情况下,假定您引用的任何类都位于同一个包中。因此,即使您将 src/添加到类路径中,它也会查找 src/ProjectName/SourceClass.class ,但它找不到。当您传递 -d target/
选项时,它会创建正确的包层次结构,从而找到该类。
相关文档来自javac official doc :
You should arrange source files in a directory tree that reflects their package tree. For example, if you keep all your source files in C:\workspace, the source code for com.mysoft.mypack.MyClass should be in C:\workspace\com\mysoft\mypack\MyClass.java.
By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with -d (see Options, below).
...
...
-d directory Set the destination directory for class files. The directory must already exist; javac will not create it. If a class is part of a package, javac puts the class file in a subdirectory reflecting the package name, creating directories as needed. For example, if you specify -d C:\myclasses and the class is called com.mypackage.MyClass, then the class file is called C:\myclasses\com\mypackage\MyClass.class. If -d is not specified, javac puts each class files in the same directory as the source file from which it was generated.
Note: The directory specified by -d is not automatically added to your user class path.
关于java从命令行编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19069163/