When I’m reading Effective Java, the author told me that a single-element enum type is the best way to implement a singleton, because we don’t have to consider sophisticated serialization or reflection attacks. This means we cannot create an instance of enum using reflection, right?
I have done some tests, with an enum class here:
public enum Weekday {}
Then I tried to create an instance of Weekday:
Class<Weekday> weekdayClass = Weekday.class;
Constructor<Weekday> cw = weekdayClass.getConstructor(null);
cw.setAccessible(true);
cw.newInstance(null);
As you know, it doesn’t work. When I change the key word enum to class, it works. I want to know why. Thank you.
This is built into the language. From the Java Language Specification (§8.9):
The whole purpose of this is to allow the safe use of
==to compareEnuminstances.EDIT: See the answer by @GotoFinal for how to break this “guarantee” using reflection.