2013-05-06 45 views
68

当我尝试用javac编译该类时,出现编译错误,并且未创建Test.class。Eclipse如何创建一个具有未解决的编译问题的类?

public class Test { 
    public static void main(String[] args) { 
     int x = 1L; // <- this cannot compile 
    } 
} 

但是当我在Eclipse中创建这个类时,我可以看到Test.class出现在target/classes中。当我尝试用java.exe的命令列运行这个班,我得到

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from long to int

确实Eclipse中使用它自己的特殊的Java编译器创建一个破碎的.class? java.exe如何知道.class中的复杂问题?

+11

+1。很好的问题,我从来没有想过:) – Maroun 2013-05-06 07:47:42

回答

64

这是Java编译器如何知道在类的编译错误。

public static void main(String[] paramArrayOfString) 
{ 
    throw new Error("Unresolved compilation problem: \n\tType mismatch: cannot convert from long to int.\n"); 
} 

如果反编译你的类文件,你可以看到类文件,该编译器产生的上述main()方法。这是因为Eclipse使用的compilerEclipse编译器for Java)与标准Java编译器不一样!

+0

因此,它不使用'javac',那么在Eclipse中删除JDK工具包中的'javac.exe'文件后,是否可以在Eclipse中编译.java文件? 只是好奇。 :) – 2013-05-06 17:34:17

+5

@ChaZ - 看看这个[问题](http://stackoverflow.com/questions/3061654/what-is-the-difference-between-javac-and-the-eclipse-compiler?lq=1 )。从那里的答案引用一行 - “Eclipse自带编译器的事实也很明显,因为您可以在Eclipse中编写,编译和运行Java代码,而无需安装Java SDK。”希望能够解决您的好奇心! – SudoRahul 2013-05-07 03:18:36

+0

:的确如此。 ;) – 2013-05-07 10:05:20

41

Eclipse中使用IBM编译器,具有产生不编译类的选项,与

throw new Error(); 

恕我直言更换的错误,这是非常不好的做法,我已经看到了一些非常贫穷的优质项目使用。该项目一次不会完整编译数周。

不像失败的快速策略,尽量减少错误的成本,尽可能迟的发现错误也最大限度地解决它们的成本。

只有在您快速编写原型代码时,此策略才有效,即您知道的代码永远不会投入生产。 (很难确定情况如何)

+13

听起来像死亡的电话给我。在编写代码时,我经常尝试,并且我认为大多数人应该尝试在编译时让代码中断,而不是让它成为bug并在生产中崩溃。现在明显的编译时错误被允许隐藏起来,这可能是杀手/ – mawia 2013-05-06 07:44:03

+2

我认为与所有内容辅助,自动更正,突出显示,包资源管理器,...提供你几乎不能错过的错误。 从我的角度来看,测试不能编译的类是可以的,例如在你实现一个接口之后,你将不得不编写几个无用的返回来测试一个单一的方法......我认为这会导致讨厌的讨论,我只是想提供一个替代方案。 – 2013-05-06 07:50:01

+1

@FranzEbner应该没有机会运行代码,甚至不会编译。 ;)恕我直言,Mocking代码是处理测试中接口的更好方法。 – 2013-05-06 07:53:08

26

是的,Eclipse使用它自己的特殊编译器;称为“ecj”。从堆栈溢出问题What is the difference between javac and the Eclipse compiler?

One notable difference is that the Eclipse compiler lets you run code that didn't actually properly compile. If the block of code with the error is never ran, your program will run fine. Otherwise it will throw an exception indicating that you tried to run code that doesn't compile.

相关问题