java – 为什么为每个枚举类型创建不同的类文件,如果它们具有常量特定的方法?
作者:互联网
我有一个枚举
enum OperationsType {
ADD("+"), SUB("-"), DIV("/"), MUL("*");
private String opcodes;
private OperationsType(String opcodes) {
this.opcodes = opcodes;
}
public String toString() {
return this.opcodes;
}
}
这里所有枚举类型都没有任何常量的特定方法,因此javac只为枚举创建一个类文件
OperationsType.class
但如果我在所有枚举类型的相同代码中添加常量Specific方法,则javac将创建5个类文件.
Operations.class
Operations$1.class
Operations$2.class
Operations$3.class
Operations$4.class
以下代码
enum Operations {
ADD("+") {
public double apply(double a, double b) {
return a + b;
}
},
SUB("-") {
public double apply(double a, double b) {
return a - b;
}
},
DIV("/") {
public double apply(double a, double b) {
return a / b;
}
},
MUL("*") {
public double apply(double a, double b) {
return a * b;
}
};
private String opcodes;
private Operations(String opcodes) {
this.opcodes = opcodes;
}
public abstract double apply(double a, double b);
}
所以我怀疑为什么编译器为每个枚举类型创建了4个不同的类,如果它们具有常量的特定方法但是如果它们没有常量的特定方法则不创建不同的类?
解决方法:
具有常量特定方法的枚举是使用匿名内部类实现的.如The Java Language Specification中所述:
The optional class body of an enum constant implicitly defines an
anonymous class declaration (07001) that extends the immediately
enclosing enum type. The class body is governed by the usual rules of
anonymous classes; in particular it cannot contain any constructors.
匿名内部类是通过创建类名为OuterClass $1,OuterClass $2等的类文件来实现的,这正是枚举的情况.
标签:class-file,java,enums 来源: https://codeday.me/bug/20190824/1710529.html