我有3个班级:
class Base {...}
class Derived1 extends Base {...}
class Derived1 extends Base {...}
我想提供创建派生类的新实例的方法:
@Inject @New
Instance<Base> instance;
public <T extends B> T create(Class<T> clazz) {
return instance.select(clazz).get();
}
但它不起作用。 instance
能够创建注入点指定的Base
类实例。
从概念上讲,我想注入Instance<? extends Base>
,但似乎不支持。
答案 0 :(得分:0)
当然我错误地建议你使用@Inject @Any @New
......你应该使用@Inject @Any
。
我在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();
}
}
<强>结果:强>
DefaultHelloService: Hello World!OtherHelloService: Hello World!