0

I have this abstract class

public abstract class GenericScheduleController implements Serializable {

    @Inject
    private Service service;

    @PostConstruct
    private void init() {
        service.doSomething(getLabel());
    }

    protected abstract String getLabel();
}

and I would like programmatically inject a new one dynamically.

public <T extends GenericScheduleController> T getScheduleController(String chaine) {
    //TODO
    //get new CDI instance programmatically with abstract getLabel() return chaine
}

Is it possible ?

Thx

olivier P
  • 9
  • 3

2 Answers2

0

I think what you're looking for is Instance:


@Inject
Instance<GenericScheduleController> instances;

public <T extends GenericScheduleController> T getScheduleController(String chaine) {
    return instances.stream()
                .filter(s -> s.getLabel().equals(chaine))
                .findAny()
                .orElse(null);
}


Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26
  • thx for reply But I don't have any GenericScheduleController in my application. I would like create new one "one the fly" programmatically. – olivier P Oct 13 '22 at 09:14
-1

I do this and it's ok

public abstract class GenericScheduleController implements Serializable {

    @Inject
    private Service service;

    @PostConstruct
    private void init() {
        if (getLabel() != null) {
                service.doSomething(getLabel());
        }
    }

    protected abstract String getLabel();
}



@Named
public class FooScheduleController extends GenericScheduleController  {

    private String label;

    @Override
    public String getLabel() {
        return label;
    }

    public void refreshInit(String label) {
        this.label = label;
        super.init();
    }
}


@Named
@ViewScoped
public class ReportingSchedulerMenuController implements Serializable {

    @Inject
    private FooScheduleController fooScheduleController;

    public GenericScheduleController getScheduleController(String chaine) throws Exception {
        if (fooScheduleController.getValue() == null) {
            fooScheduleController.refreshInit(chaine);
        }
        return fooScheduleController;
    }
}
olivier P
  • 9
  • 3