Java中的编译接口

时间:2011-10-10 22:37:40

标签: java jvm javac

我刚刚发现了这一点,我希望有人知道发生了什么。要遵循的命令(在临时目录中运行,事先清除所有内容):

没问题:

cat << EOF > Myface.java
public interface Myface {}
EOF

cat << EOF > Myclass.java
public class Myclass implements Myface {}
EOF

javac Myface.java
javac Myclass.java

Myclass不会编译:

cat << EOF > Myface.java
package Mypackage;
public interface Myface {}
EOF

cat << EOF > Myclass.java
package Mypackage;
public class Myclass implements Myface {}
EOF

javac Myface.java
javac Myclass.java

Myclass不会编译:

cat << EOF > Myface.java
package Mypackage;
public interface Myface {}
EOF

cat << EOF > Myclass.java
package Mypackage;
public class Myclass implements Myface {}
EOF

javac Myclass.java

这里发生了什么?

编辑:所有命令,运行:

javatest@l-bel-smai-ubuntu:~$ ls
javatest@l-bel-smai-ubuntu:~$ pwd
/home/javatest
javatest@l-bel-smai-ubuntu:~$ cat << EOF > Myface.java
> public interface Myface {}
> EOF
javatest@l-bel-smai-ubuntu:~$ 
javatest@l-bel-smai-ubuntu:~$ cat << EOF > Myclass.java
> public class Myclass implements Myface {}
> EOF
javatest@l-bel-smai-ubuntu:~$ 
javatest@l-bel-smai-ubuntu:~$ javac Myface.java
javatest@l-bel-smai-ubuntu:~$ javac Myclass.java
javatest@l-bel-smai-ubuntu:~$ ls
Myclass.class  Myclass.java  Myface.class  Myface.java
javatest@l-bel-smai-ubuntu:~$ rm *
javatest@l-bel-smai-ubuntu:~$ cat << EOF > Myface.java
> package Mypackage;
> public interface Myface {}
> EOF
javatest@l-bel-smai-ubuntu:~$ 
javatest@l-bel-smai-ubuntu:~$ cat << EOF > Myclass.java
> package Mypackage;
> public class Myclass implements Myface {}
> EOF
javatest@l-bel-smai-ubuntu:~$ 
javatest@l-bel-smai-ubuntu:~$ javac Myface.java
javatest@l-bel-smai-ubuntu:~$ javac Myclass.java
Myclass.java:2: cannot find symbol
symbol: class Myface
public class Myclass implements Myface {}
                                ^
1 error
javatest@l-bel-smai-ubuntu:~$ rm *
javatest@l-bel-smai-ubuntu:~$ cat << EOF > Myface.java
> package Mypackage;
> public interface Myface {}
> EOF
javatest@l-bel-smai-ubuntu:~$ 
javatest@l-bel-smai-ubuntu:~$ cat << EOF > Myclass.java
> package Mypackage;
> public class Myclass implements Myface {}
> EOF
javatest@l-bel-smai-ubuntu:~$ 
javatest@l-bel-smai-ubuntu:~$ javac Myclass.java
Myclass.java:2: cannot find symbol
symbol: class Myface
public class Myclass implements Myface {}
                                ^
1 error
javatest@l-bel-smai-ubuntu:~$ 

3 个答案:

答案 0 :(得分:1)

是的,我们走了: Java / Class文件目录结构必须与声明Java类的包结构相匹配,以便编译和类加载才能正常工作。

答案 1 :(得分:0)

编译Myclass.java时添加classpath选项

javac -classpath . Myclass.java

答案 2 :(得分:0)

案例2:编译Myclass.java时,javac会查找Mypackage/Myface.class。那不是那里。您应该使用javac -d .进行编译,使javac为它生成的类创建适当的目录结构。这也是下一次javac电话的搜索路径中的隐含意义。

案例3:编译Myclass.java时,它将查找Mypackage/Myface.class,然后查找命令行上给出的合适源文件,然后查找Mypackage/Myface.java中的合适源文件。都不存在。使用javac -d Myface.java Myclass.java进行编译或将*.java推送到包名称所指示的相应目录结构中。