1

I'm using Java EE 8 and I have next enum. The question is is it possible assign to the one injected variable the value of another injected variable within one class like on the next line?

public enum CommandEnum {

    EMPTY_COMMAND {
        {
            this.command = emptyCommand;
        }
    },
    NAME_GENERATION {
        {
            this.command = nameGenerationCommand;
        }
    },
    NAME_GENERATION_SETTINGS {
        {
            this.command = nameGenerationSettingsCommand;
        }
    },
    SIGNIN {
        {
            this.command = signinCommand; // is it possible?
        }
    };

    @Inject
    @EmptyCommandQualifier
    Command command;
    @Inject
    EmptyCommand emptyCommand;
    @Inject
    NameGenerationCommand nameGenerationCommand;
    @Inject
    NameGenerationSettingsCommand nameGenerationSettingsCommand;
    @Inject
    SigninCommand signinCommand;

    public Command getCommand() {
        return command;
    }
}

Thank you.

tohhant
  • 103
  • 10
  • 4
    `Enum`s are not created through the bean container. Therefore, I would be surprised if we were able to inject anything in an `Enum` in this way. – Turing85 Mar 20 '21 at 13:52
  • Thank you! I didn't knew that enums aren't supported by CDI – tohhant Mar 20 '21 at 15:16
  • But the question is actual, because i meant is it possible to assign injected field of one type the value of another injected field with the same type – tohhant Mar 27 '21 at 01:04

1 Answers1

1

Yes, it is possible - but only after CDI had a chance to inject a value. CDI supports @PostConstruct annotation for this purpose:

To Initialize a Managed Bean Using the @PostConstruct Annotation Initializing a managed bean specifies the lifecycle callback method that the CDI framework should call after dependency injection but before the class is put into service.

  1. In the managed bean class or any of its superclasses, define a method that performs the initialization that you require.
  2. Annotate the declaration of the method with the javax.annotation.PostConstruct annotation.

When the managed bean is injected into a component, CDI calls the method after all injection has occurred and after all initializers have been called.

Note: As mandated in JSR 250, if the annotated method is declared in a superclass, the method is called unless a subclass of the declaring class overrides the method.

Adding the method below will have an effect you are looking for:

@PostConstruct
public void init () {
    this.command = signinCommand;
}
Illya Kysil
  • 1,642
  • 10
  • 18