制作Java包 [英] Making java packages
问题描述
我的Java类组织有些混乱,所以我要讲的是我在Java学习中跳过的一些事情:类路径。我无法安静地让心爱的类在我为他们创建的包中进行编译。这是我的文件夹层次结构:
My Java classes organization has gotten a little messy so I'm going over something I've skipped in my Java learning: the classpath. I can't quiet get beloved classes to compile in the packages I have created for them. Here's my folder hierarchy:
.
com/
david/
Greet.java
greeter/
SayHello.java
SayGoodbye.java
其中SayHello的构造函数仅打印 hello,SayGoodbye的打印 Goodbye,而Greet的main方法仅创建这两个对象。 SayHello的顶部是com.david.greeter包;并且与SayGoodbye和Greet's同样是com.david软件包;
Where SayHello's constructor just prints "hello" and SayGoodbye's prints "Goodbye" and Greet's main method just creates those two objects. At the top of SayHello is package com.david.greeter; and likewise with SayGoodbye and Greet's is package com.david;
在greeter文件夹中,我能够编译两个java文件,但是如果我转到当前目录(目录包含com),并执行javac -cp com.david.greeter。* com / david / Greet.java,它表示找不到类,并且说包com.david.greeter不存在。我也尝试过手动设置$ CLASSPATH。
In the greeter folder I was able to compile both java files but if I go to the current directory (the directory that holds com) and do javac -cp "com.david.greeter.*" com/david/Greet.java it says it can't find the classes as well as saying package com.david.greeter doesn't exist. I've also tried setting the $CLASSPATH manually.
我的机智就在这里,Stackoverflow(就像我在这里发帖时一样)。你们中有人知道我在做什么吗?
I'm at my wit's end here, Stackoverflow (as I normally am when I post here). Do any of you know what I am doing wrong?
推荐答案
java编译器将遍历classpath的子目录以寻找
The java compiler will traverse the sub-directories of the classpath looking for the packages it needs.
因此,您的命令行应如下所示:
So, your command line should be as follows:
javac -cp "." com/david/Greet.java
当编译器看到对com.david.greeter.SayHello的引用时在编译Greet.java时,它将从类路径中的目录开始,并遍历层次结构以查找所需的包。
When the compiler sees a reference to com.david.greeter.SayHello while compiling Greet.java it will start with the directory in the classpath and traverse the hierarchy looking for the package it needs.
这篇关于制作Java包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!