大家好,
最近使用ANT编译工程。做了一个简单的实验,发现javac task在处理java代码中的import语句时出错,导致便以失败。import一个在根目录下的class(即没有包名前缀)时,会提示输入.(包名分隔符)。难道java代码不允许子文件夹里的类调用其父文件夹中的类?但为何我将代码放入Eclipse时,却没有问题呢?有谁遇到过这样类似的问题么?怎么解决的呢?希望能得到大家的帮助。
附件中是代码和build.xml以及输出的log信息。
源代码很简单,一个A.java一个com/B.java。
//A.java
import com.*; public class A{ public static void test(){ System.out.println("A.test()"); } public static void main(String[] args){ System.out.println("Hello!"); } }
//com/B.java
package com; import A; //编译错误产生的地方 public class B{ public static String out(){ A.test(); return "This is B!"; } }
//build.xml
<project name="Test" default="compile" basedir="."> <target name="compile"> <javac includeantruntime="false" listfiles="true" includeDestClasses="false" srcdir="src" destdir="class"> <classpath> <pathelement path="class"/> </classpath> </javac> </target> </project>
主要是因为你的A是在默认包下。jdk从1.4开始就不支持从默认包导入类了。你把类A移到一个有名字的包下就可以了,如com.A。
[quote]The compiler now rejects import statements that import a type from the unnamed namespace. Previous versions of the compiler would accept such import declarations, even though they were arguably not allowed by the language (because the type name appearing in the import clause is not in scope). The specification is being clarified to state clearly that you cannot have a simple name in an import statement, nor can you import from the unnamed namespace.
To summarize, the syntax
import SimpleName;
is no longer legal. Nor is the syntax
import ClassInUnnamedNamespace.Nested;
which would import a nested class from the unnamed namespace.[/quote]
参考:[url]http://java.sun.com/javase/compatibility_j2se1.4.html#incompatibilities1.4[/url]
我把你的代码拷到eclipse里也是会报编译错误的。除非你的compile compliance level 是1.3的。