Java enum synthetic arguments for constructors

gudge picture gudge · Jun 9, 2014 · Viewed 9.6k times · Source

Please have a look at Synthetic Arguments. Enum constructors have two additional synthetic arguments.

Please look at the section:

Another example: Java enum classes

As you can see, it saves quite some code, but also adds synthetic fields, methods and constructor parameters. If you had defined your own constructor, with its own set of parameters.

Can there be a situation where a enum constructor does not have any synthetic arguments.

Apologies for not providing enough detail.

Answer

Duncan Jones picture Duncan Jones · Jun 9, 2014

Having read the article, I would say the answer is no. The article explains that a typical enum such as:

enum Colours {
    RED, BLUE;
}

Becomes:

final class Colours extends java.lang.Enum {
    public final static Colours RED = new Colours("RED", 0);
    public final static Colours BLUE = new Colours("BLUE", 1);

    private final static values = new Colours[]{ RED, BLUE };

    private Colours(String name, int sequence){
        super(name, sequence);
    }

    public static Colours[] values(){
        return values;
    }

    public static Colours valueOf(String name){
        return (Colours)java.lang.Enum.valueOf(Colours.class, name);
    }
}

where the arguments to the Colours constructor are considered synthetic (i.e. they've been produced by the compiler to make sure "stuff works"). So it seems the synthetic arguments are unavoidable as they're a necessary part of translating an enum into a real class.

The only possibility is if the enum has no values - does Java still create the synthetic fields? Intuitively, the answer is yes. This is backed up by the article in the OK, but why should I care? section. Here the author shows that an empty enum still has a parameter count of two, when viewed with reflection.