简体   繁体   English

如果编译一个空的Java文件会怎样?

[英]What happens if you compile an empty java file?

When I compiled an empty Java file it didn't produce any class file. 当我编译一个空的Java文件时,它没有产生任何类文件。 So I want to know how compiler react when compiling an empty Java file? 所以我想知道编译器在编译一个空的Java文件时如何反应? I thought it should generate an empty class file in this case, but it did not. 我认为在这种情况下,它应该生成一个空的类文件,但事实并非如此。 So why it didn't? 那么为什么不呢?

javac starts, sees there is no class declared in the file, and finishes. javac启动,看到文件中没有声明任何类,然后完成。 In order for a .class file to be created you must at least have the class declaration in the file. 为了创建.class文件,您至少必须在文件中包含类声明。

What most of the answers are saying is really that a class file is not a compiled java file but a binary representation of a class. 大多数答案在说什么,实际上是一个类文件不是一个已编译的Java文件,而是一个类的二进制表示形式。

Compiling a java file could result in two class files if the java file contains two classes (although only one can be public) and that is why compiling something with zero classes will result in zero class files. 如果Java文件包含两个类(尽管只有一个可以公开),则编译Java文件可能会导致两个类文件,这就是为什么编译具有零类的内容将导致零类文件的原因。

Well given that a Java file could be like this: 考虑到Java文件可能是这样的:

// Foo.java 
class Bar
{
}

How would it know what to call the thing? 它怎么知道该叫什么呢? Also should it make it a class or an interface or an enum? 还应该使其成为类,接口或枚举吗?

Rather than make the choice for you it does nothing (I would have expected an error myself... but nothing is a sane thing to do as well). 它没有为您做出选择,它什么也不做(我本来希望自己犯一个错误……但是什么也不是理智的事情)。

If the file is totally empty and just called .java then there is nothing for the compiler to do when you attempt to generate a class file. 如果文件完全为空,并且仅调用.java,则在尝试生成类文件时,编译器将无任何操作。 If you do have a 如果你有一个

class Foo {
}

segment in the .java file then an empty calss file (Foo.class) will be generated .java文件中的段,然后将生成一个空的calss文件(Foo.class)

javac creates a class file for each class declaration (explicit or anonymous). javac为每个类声明(显式或匿名)创建一个类文件。 since your java file contained none, the compiler justly didn't generate any class files. 由于您的Java文件不包含任何文件,因此编译器完全不会生成任何类文件。

If you would've declared the class, (eg, public class test{ } ), it would compile and create test.class file. 如果您已经声明了该类(例如, public class test{ } ),它将编译并创建test.class文件。 It would not run b'cos it doesn't have a main method. 它没有main方法,将无法运行。

class Emptyclass { } 类Emptyclass {}

//Emptyclass can be compiled sucessfully and .class file is also generated, but during execution it fails, because JVM doesnot find 'Main Method' in class 'Emptyclass' // Emptyclass可以成功编译,并且还会生成.class文件,但是在执行过程中会失败,因为JVM在类'Emptyclass'中找不到'Main Method'

Java will not create class file of that java file. Java不会创建该Java文件的类文件。 Because First it will look for class name. 因为首先它将查找类名称。 So nothing will happen 所以什么都不会发生

Javac启动并检查文件的大小,如果大小为零,则它仅返回而未创建任何.class文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM