Java enum attributes returning null based on order of access

前端 未结 2 1306
盖世英雄少女心
盖世英雄少女心 2021-01-21 09:58

I was exploring enums in java to see how they could be abused and I came across a behaviour I couldn\'t explain. Consider the following class:

public class PROGR         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-21 10:25

    When you call ENUM.ANIMALS.CATS.GARFIELD.RIVAL, it will start by creating the CATS enum. When processing the first element, FELIX, it needs to create the DOGS enum so that DOGS.AKAME can be passed as a parameter to the CATS constructor.

    The DOGS constructor receives a parameter of type CATS, but since CATS was not yet initialized all CATS.something will return null, thus setting the RIVAL attribute to null for all elements in the DOGS enum.

    When all DOGS elements are created, it goes back to CATS and resumes the creation of its elements, passing the just created DOGS elements as parameters.

    Similarly, when you invert the order of the calls it starts by creating the DOGS enum which causes the CATS elements RIVAL attribute to be set as null.

    If this is not clear, try to run your code with breakpoints set at the enum elements' declarations and at the constructors to understand it better.

提交回复
热议问题