Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java lazy loading of enum instances

If I have a bunch of enum instances in an enum type, and if I access an instance of it the first time, all of its remaining instances too are initialized at the same time. Is there any way to initialize an enum instance only when it's accessed the first time?

like image 391
shrini1000 Avatar asked Feb 23 '12 06:02

shrini1000


2 Answers

Not without basically making it not an enum anymore. Enums are classes. The first time a class is used, it gets loaded by the JVM and all of its static initialization is done. Setting up the enum members is a static initialization, so they're all going to be initialized.

like image 139
T.J. Crowder Avatar answered Oct 30 '22 02:10

T.J. Crowder


You can make the instances lazy loading on use. i.e. the constructor doesn't actually perform the expensive work. In the methods for these enums, you add a checkingLoaded() method to the methods which need this. This doesn't have to be every method depending on what it does.

like image 33
Peter Lawrey Avatar answered Oct 30 '22 02:10

Peter Lawrey