简体   繁体   中英

Cast Bean<?> from BeanManager to class instance in Servlet

I have an EJB project, and have the following annotation:

@Retention(RUNTIME)
@Target(TYPE)
@Qualifier
public @interface AfterComplete {
}

I have 2 classes that are decorated with this annotation. They are also @Stateless

@AfterComplete
@Stateless
public class AfterCompletePrinter implements IAfterComplete {

  public void afterComplete(String someValue) {
    System.out.println("After complete printer: " + someValue);
  }

}


@AfterComplete
@Stateless
public class AfterCompleteErrPrinter implements IAfterComplete{

  public void afterComplete(String someValue) {
    System.err.println(someValue);
  }
}

In a servlet, I have:

@WebServlet("/")
public class DemoServlet extends HttpServlet {
  @Inject
  BeanManager beanManager;

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Set<Bean<?>> beans = beanManager
        .getBeans(Object.class,new AnnotationLiteral<AfterComplete>() {});

    for (Bean<?> bean : beans) {
      response.getWriter().print(bean.getBeanClass());
      // IAfterComplete iac = (IAfterComplete) bean;
    }
  }
}

My servlet prints:

net.mikeski.ejb_annotations.AfterCompletePrinterclass net.mikeski.ejb_annotations.AfterCompleteErrPrinter

However, this line throws an exception if it's not commented:

IAfterComplete iac = (IAfterComplete) bean;

The exception is:

java.lang.ClassCastException: org.jboss.weld.bean.SessionBean cannot be cast to net.mikeski.ejb_annotations.IAfterComplete

How can I do something with bean to get the instance of the class that implements IAfterComplete ? The bean.getName() returns null.

I was thinking if I can get its JNDI name I can do a lookup, but don't see how to do that.

This is Wildfly 10 if it makes any difference.

So, I found the answer that works, it's done like this:

@Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Set<Bean<?>> beans = beanManager
        .getBeans(Object.class, new AnnotationLiteral<AfterComplete>() {
        });

    for (Bean<?> bean : beans) {
      response.getWriter().print(bean.getBeanClass());
      IAfterComplete iac = (IAfterComplete) beanManager.getReference(bean, IAfterComplete.class, beanManager.createCreationalContext(bean));
      iac.afterComplete("After complete called on " + iac);
    }
  }

I put the whole working project on github here: https://github.com/mikebski/ejb-custom-annotations

Here's a quick blog post with a little more of an explanation:

http://blog.mikeski.net/blog_post/487

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM