How to create an instance of enum using reflection in java? -


when i'm reading "effective java", author told me single-element enum type best way implement singleton, because don't have consider sophisticated serialization or reflection attacks. means cannot create instance of enum using reflection, right? have done test, enum class here:

    public enum weekday {} 

then tried create instance of weekday:

    class<weekday> weekdayclass = weekday.class;     constructor<weekday> cw = weekdayclass.getconstructor(null);     cw.setaccessible(true);     cw.newinstance(null); 

as know, doesn't work. when change key word "enum" "class", works. want know why. thank pre.

this built language. java language specification (§8.9):

it compile-time error attempt explicitly instantiate enum type (§15.9.1). final clone method in enum ensures enum constants can never cloned, , special treatment serialization mechanism ensures duplicate instances never created result of deserialization. reflective instantiation of enum types prohibited. together, these 4 things ensure no instances of enum type exist beyond defined enum constants.

the whole purpose of allow safe use of == compare enum instances.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -