不使用 IDE 时的 Java 和编译
我知道在java中你被迫为每个类一个文件。
因此,如果我有这样的类:
/my_project/main.java
/my_project/classes/user.java
/my_project/classes/other.java
并且我的 main.java 引用了用户和其他文件,我将如何通过命令行编译它?
如果我要引用外部 .jar,并将它们放在特定文件夹中,我如何才能将其包含在编译中? (或者有一个通用的地方我可以把它们放在会自动拾取的地方,就像 python 是如何做到这一点的)
I understand in java that you are forced into a single file per class.
So if I have classes like:
/my_project/main.java
/my_project/classes/user.java
/my_project/classes/other.java
And my main.java references the user and other files, how would I compile this via the command line?
If I was to have external .jar's that I was referencing, and I placed them in a particular folder, how could I also include this in my compiling? (or is there a general place I can put them where they will be picked up automatically like how python does this)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要编译,您需要从 my_project 文件夹中指定每个源文件:
您还可以使用 -cp 选项为类路径指定 jar 文件:
您可能还需要摆弄 -cp 标志以确保您的类文件夹是在类路径中。
to compile, you will need to specify each source file, from the my_project folder:
You can also specify jar files for your classpath with the -cp option:
You may also need to fiddle with the -cp flag to make sure your classes folder is in the classpath.
首先,Java 类以小写字母开头是很糟糕的风格。
只有公共类需要位于它们自己的文件中,但您可以根据需要将任意数量的包私有类添加到同一个文件中(尽管这被视为不良风格)。
也就是说,编译代码的最简单方法是:
在任何情况下,正确的代码布局应该是类位于与其包匹配的目录结构中。
编辑:这里有一个相当好的约定解释http://www.article.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter05/packagesImport.html
First of all it's poor style to make Java classes starting with lowercase.
Only public classes need to be in their own file, but you can add as many package-private classes as you like to the same file (although this is seen as poor style).
That said, the easiest way would to compile your code would be:
In any case, proper code layout should be that classes are in a directory structure matching their package.
EDIT: There is a fairly good explanation of conventions here http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter05/packagesImport.html
除了上面的答案之外,您还可以使用 Apache Ant 之类的东西,以便更轻松地配置您的构建(如果它变得复杂)。
In addition to the above answer, you can use something like Apache Ant, for easier configuration of your build (if it gets complicated).
查看 javac 的文档。您可以传递多个源文件,或指定源目录。
Look at the documentation for javac. You can pass multiple source files, or specify the source directory.