2
votes

I have 3 classes:

class Base {...}
class Derived1 extends Base {...}
class Derived1 extends Base {...}

I want to provide method creating new instances of derived class:

@Inject @New
Instance<Base> instance;
public <T extends B> T create(Class<T> clazz) {
    return instance.select(clazz).get();
}

but it does not work. instance is able to create instances of Base class as specified at injection point.

Conceptually I would like to inject Instance<? extends Base> but it seems to be not supported.

1
Please try to use @Inject @Any @New.Arek
It also does not work. It is not possible to combine those qualifiers together.Karol

1 Answers

0
votes

Of course I've made a mistake suggesting you that you should use @Inject @Any @New... You should use @Inject @Any.

I've tested it on Glassfish 4.1.

HelloService.java

import javax.enterprise.context.Dependent;

@Dependent
public class HelloService {

    public String getMsg() {
        return "Hello World!";
    }
}

DefaultHelloService.java

import javax.enterprise.context.Dependent;

@Dependent
public class DefaultHelloService extends HelloService {

    public String getMsg() {
        return "DefaultHelloService: Hello World!";
    }
}

OtherHelloService.java

import javax.enterprise.context.Dependent;

@Dependent
public class OtherHelloService extends HelloService {

    @Override
    public String getMsg() {
        return "OtherHelloService: " + super.getMsg();
    }
}

MainServlet.java

@WebServlet(name = "demoServlet", urlPatterns = "/demo-servlet")
public class MainServlet extends HttpServlet {

    @Inject @Any
    Instance<HelloService> instance;

    public <T extends HelloService> T create(Class<T> clazz) {
        return instance.select(clazz).get();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        writer.append(create(DefaultHelloService.class).getMsg());
        writer.append(create(OtherHelloService.class).getMsg());

        writer.flush();
    }
}

Result: DefaultHelloService: Hello World!OtherHelloService: Hello World!