6

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?

shrini1000
  • 7,038
  • 12
  • 59
  • 99
  • Why would you want that? – T.J. Crowder Feb 23 '12 at 06:51
  • 1
    I don't have a concrete use case for this, but was wondering - if it's expensive to create an enum instance (say it reads something from DB per instance creation), then it may make more sense to create an instance only when it's asked for. – shrini1000 Feb 23 '12 at 06:53
  • 1
    I have a very specific case. I need to store enum if image objects that will be searched in a computer vision project. They are likely to be searched multiple times, but I don't want to initialise them along with the application. – Tomáš Zato Feb 05 '15 at 19:44

2 Answers2

11

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130