Strategy: Using reflection to invoke EJB


J2EE patterns: Strategy: Using reflection to invoke EJB

  1. Strategy: Using reflection to invoke EJB (36 messages)

    We know about reflection. The same idea would like to extend for EJBObject...i.e. how a particluar client[servlet/pojo] can invoke a method on another session bean without importing its Home/Remote?

    i.e. the client is linked to EJB at compile time but at run-time.

    In Plain Java world one needs to delegate call to instances that are in same JVM.
    In EJB instances are distributed and ,the client does not have reference to instances.
    But client does have reference to STUB.A stub by defination is proxy for remote
    aka distributed instances.So if you can delegate calls to stub...youcan delegate call to remote instances..
    Then the question is how does one get access to Stub... ..the answer is with the help of EJBMetaData..for example

    you have a session bean : MySessionHome/MyRemote/MyBean..3 classes..
    Now MyRemote has a simple method :"getYourMessage()"

    now study the code without reflection and then with reflection..

    import MyHome;
    import MyRemote;
    import javax.ejb.*;

    public Class client_without_reflection {

    public static void main(String args[]){
    //1. create initial context
    Properties h = new Properties();
    h.put(Context.PROVIDER_URL, url);
    Context c = new InitialContext(h);
    //2. look-up home
    Object home = ctx.lookup(JNDI_NAME);
    MyHome myHome =(MyHome) PortableRemoteObject.narrow(home, MyHome.class)

    //3. create the remote
    MyRemote myRemote =
                            (MyRemote) myHome.create();
    //4. use the remote
    String message = myRemote.getMessage();



    import javax.ejb.*;
    //no-need to import anything..!!
    public Class client_ejb_reflection {

    public static void main(String args[]){
    //1. create initial context
    Properties h = new Properties();
    h.put(Context.PROVIDER_URL, url);
    Context c = new InitialContext(h);
    //2. look-up home
    Object home = ctx.lookup(JNDI_NAME);
    EJBHome theHome =(EJBHome) PortableRemoteObject.narrow(home, MyHome.class)

    //3. create the remote

    EJBMetaData md =
    Class homeClass =
    EJBObject theRemote = (EJBObject)

    //4. use the remote
    Class remoteClass =
    String message =

        static Object invoke(Class c,Object obj,String mname){
          Method[] methods = c.getMethods();
          String name=null;
          Object r= null;
          try {
              for(int i = 0; i<methods.length ;i++) {
                 name = methods[i].getName();
                 if(name.startsWith(mname)) {
                    r = methods[i].invoke(obj,null);
          } catch(Exception e){
          return r;

    The crux is EJBMetaData which gives access to ACTUAL REMOTE CLASS...!!

    And this Time i have tested the code with Jboss and Weblogic 8.1!(;

    Rarley one would use such reflection-techniques to right the business code..
    then where it is usefull..

    1. IDE/Deployment Tools.. Just refere EJBMetaData javadoc.its enlightning.
    2. Scheduler products like Kronova...can invoke any method on any Session per allows GUI to define an EJBTask.visit
    3. Business-Rule-Engine.
    4. !!!
    5. !!!

    It would be great if we can find some REAL USAGE Scenarios.

    Note:this technique should be avoided to be used from within Session Bean as per EJB Spec.

    Threaded Messages (36)

  2. This will be ok since it is from EJbMetaData and nothing to do with spec..

    It is very useful...

    since ejb is corba compatibe we need to use
    MyHome myHome =(MyHome) PortableRemoteObject.narrow(home, MyHome.class)

    so if u want to change a method name it is very difficult u have change the stub..

    In this case u can add a new method with the help of an xml or property file..

    we can reduce the dependeny..Ithink..
    plse give ur mail id
  3. Useful or not...[ Go to top ]

    Well, sometimes it is important to create frameworks.
    In one of the last companies, I have worked for, I used
    the ServiceLocator Pattern and implemented it using reflection.
    The Business Developers don't know a heck of a lot about EJB
    and J2EE but merely use a generator to create their services.
    If they are to call an EJB in the Code, they usually ask the
    Architecture department on how to do this.

    The services are usually stateless, the Service Locator itself
    does not need to know about the Remote Object's implementation class or
    interface. Merely, the client does know about the business functionality
    The Client (in the last company's case) needs
    to know about the service, but not the Service Locator or EJB.
    If you, however, want to decouple the EJB Call functionality and
    not involve the actual business software developer, you can merely
    introspect the Remote Object and call the create method (of course,
    after narrowing). This will leave your Service Locator code without
    knowing the actual Remote Interface type. All it needs to know is that
    there is a create() method on the Home Interface returning an EJBObject or

    EJBObject getService(String serviceName) throws RemoteException, NoSuch...
    EJBLocalObject getLocalService(String serviceName) throws NoSuchServiceExc...

    Now, think about defining a base class from which all services inherit.
    Then you can even decouple more.

    BaseService getService(String svcName) throws RemoteException, NoSuch...
    BaseService getLocalService(String svcName) throws NoSuchServiceExc...

    I strongly advise business developers to be familiar with EJBs and client
    calling conventions, etc. However, sometimes companies restructure and
    try to establish a development group using Cobol Programmers. And some-
    times the same have a problem learning using them on EJB projects
    can be quite stressful.

    The question is if this is still useful with JDK 1.5
    where you have dynamic proxies and the @remote tag to demarcate remote
    objects and methods. The dynamic proxy would here give you access to the
    methods of the Remote Object and mirror the stub's functionality.

    Another use for reflection with EJB would be the Command Pattern.
    Many IT Companies still use the command pattern for Generic Services.
    Here it might be useful just to know what service to delegate to.
    This can be done using some sort of configuration file or source.
    However, implementing the Command Pattern with EJB, always depends
    on the circumstances.

  4. UsageScenarios

    1. IDE/Deploymemnt Tools
    2. Business Rule Engine[Scheduler may invoke this Engine periodically]

    3. Command Engine Delegation
    4. Implementation Strategy for Service Locator

    *5. Generalized EJB Test Case(s).......!
  5. <ejb-metadata-javadoc>
    The meta-data is intended for development tools used for building applications that use deployed enterprise Beans,

    for clients using a scripting language to access the enterprise Bean.


    this implies.we can extend JSTL to have something like

    <jstl:invokeEjb ejbHome="org.gro.rgo.HelloEjbHome",ejbRemote="org.gro.rgo.HelloEjb" >
          blah would require something more here to generalize...
  6. I have used a business delegate that used reflection:
  7. JdonSD framework include this function[ Go to top ]

    JdonSD framework include this function, it is in
    , sorry , it is in chinese now.
  8. We've been using Java 2 proxies for a while to wrap all our EJB local/remote objects, plus singletons and web services - sort of service oriented micro container.
    This technique - as long as you define your business interface hierarchy right - masks the actual service/component implementations from client code.
    It can be an EJB, singleton or even WebService invocation. Client thinks that they operate on POJOs - until they see the first stack trace obviously :-)
  9. Have you ever heard of Spring framework?

    Spring framework takes advantage of the Dynamic Proxies to wrap your EJB calls under a Proxy class. They have StatelessSessionBean proxies which automatically create new instances of the session bean and invokes their methods. All you have to do is to "get" the proxy of have it "injected" into your client by spring framework. The proxy depends on the fact that you have abstracted out your business methods from the Remote into a business interface.
  10. Yes I did. Our framework was developed way before Srping - seems to be simmilar, however we provide specific handler application to do things like access controll enforcement, access policy definition (thru component descriptors), tracing and tracing definition and whole bunch of other things.
  11. Yes I did. Our framework was developed way before Srping - seems to be simmilar, however we provide specific handler application to do things like access controll enforcement, access policy definition (thru component descriptors), tracing and tracing definition and whole bunch of other things.
    Spring's EJB access functionality is integrated with its AOP framework. So it's easy to add such custom behaviour.
  12. Hello all.
    Thanks Rod for participating.Well it is infact SPRING that has attracted you and not the
    basic idea of reflection,i think.But its still great to see your response in thread.

    I am still dabbler in the field IOC and SPRING.Its a great idea.It relives the client-tier from
    protocol specific drudgery.And a great thing for client-side of Service Oriented Architecture.
    I wish to ask/discuss 2 issues

    A. Service Oreinted architecture is the buzz word.[SPRING] IOC solves problem for client side.
    What if i want to expose my servic,implemented as a POJO , over different protocols like
    RMI/JMS/HTTP/SOAP/Custom,without much-coding.Does SPRING Solves this trouble also?
    IOC solves the troubles of client-side-of-SOA.What about Server side of SOA??

    B. only-reflection-based-approach
    IOC/SPRING essentially provides following advantages :
    1. Client dont care of How part of just happens.
       [Boy gets his Kissable Girl.How?Who cares?!}.So tommorrow if the same service
       is to be accessed over EJB/LOCAL/SOAP etc...client just does n0t modify.simply kewl.
    2. Strong-Typed-Ness is preserved as Interfaces are at the hub of IOC.[am i right here?]

    Not the down side but,i think, we still have to code the client tier and supply with configuration.
    The ejb-reflection here i think can be taken as an alternative with the following "lofty" objective :
    "Imagine a client tier with only one class." Lets assume that ,for the time-being,our business tier is realized
    using set of session beans[local/remote/both]. the idea is extensible to POJO and SOAP also.The solution
    will lack the characterstic 2 of IOC as reflection-code will not be compile time safe.

    Solution : very briefly..i am describing here..this can be/will be strctured well [,,soon hopefully]

    1. ServiceDefinations.xml :
    consider following,raw,ServiceDefination.xml..showing only one service at the moment
    <service authenticate="true"
    <Param name="alias"
    type="java.lang.String" />

    <output type="um.User" />

    2. Lets develop Service delegator that uses this service.xml and ejb-reflection to invoke.
    The client-tier is realizable with this service delegator only.

    Spring IOC is great.proven.
    this ONLY-reflection based-APPROACH needs to prove itself though. But its an alternative.AOP can also be applied to this idea[am i right here??]

  13. No need for imports?[ Go to top ]

    In the reflection code:

    //2. look-up home
    Object home = ctx.lookup(JNDI_NAME);
    EJBHome theHome =(EJBHome) PortableRemoteObject.narrow(home, MyHome.class)

    you're still referencing MyHome.class.
  14. No need for imports?[ Go to top ]

    replace it with..
    this.theHome = (EJBHome) PortableRemoteObject.narrow(obj,EJBHome.class);
  15. Hello:

    I read your code on using reflection to call methods on EJB's. it's innovative and enlightening. How could you get creative like this? Give me hints of this kind for EJB and Java/JSP in general. My id is
  16. Hello Vimarsh,

    I have used invoking EJB with reflection on WL, WebSphere and JBoss earlier (versions 5.1, 3.X and 2.3 resp). This was for a Workflow product where I needed dynamic discovery and invocation of EJBs on either of app servers and here are my two cents.

    With the earlier versions of app servers it was possible to dynamically discover the EJB objects without even having stub classes on the client and invoke them too.
    With the introduction of CORBA compliance for EJBs it's now mandatory to have the stubs (and interface) on the client side. EJBs standard has not evolved in direction of dynamic discovery.
    Such techniques are really handy in applications like the one I worked on. It would be good if EJB comes up with a true DII.

    Best Regards,
    Mandar Joshi
    (mailto:mandar dot joshi at lntinfotech dot com)
    (mailto:joshimandar at yahoo dot com)
  17. Hi vimarsh vasavada,
      i tried to execute your code, but i am getting complie time erroe.
     the error show the this.theHome.getEJBMetaData() is not valid package. when
    i removed the this, and tried with theHome.getEJBMetaData() it does not give compile time error
      the code is :

       //3. create the remote
       EJBMetaData md = this.theHome.getEJBMetaData();

    could you please clarify me doubts.
    Thanks and regards
    Anna Madhusudnanan
  18. I wrote a EJB and client for test.

    I follow the sample code you offered and make little change. However, after I run the programme, it returns an Exception...

    here is the Exception message.

    javax.naming.CommunicationException. Root exception is java.lang.ClassNotFoundException: chapter6.account.AccountHome (no security manager: RMI class loader disabled)

    the Exception is caused by
    Object obj = ctx.lookup("AccountHome");//<-------------- this line
    EJBHome home= (EJBHome)
    PortableRemoteObject.narrow(obj, EJBHome.class);

    did you put your client, home, remote class under the same folder?

    I am using JBoss and J2SE 1.4 SDK and J2EE 1.3SDK ....

    thank you very much:)
  19. Hii
    I have some doubts regarding the reflection implementation.

    1) Is this implementation is for a distributed (web-server and app-server running on different machines) ?

    2) What is this MyHome.class ?

    3) MyHome.class is the parent interface for all Home interfaces ?

    4) How this class is going to be packaged along with the web-tier components ?

  20. This is Great[ Go to top ]

    This is really Great !!!
         It useful in sinarios , where there are 10-15 different ejb services i want to use in a sinle client (typical case with reports , where requirments heavely changes :)) , then y to write code for looking those different home interfaces ?? .. just a generic function with reflection is enough .. !
  21. Hi,
        Does this mechanism apply to ONLY remote interfaces ???
    B/c i tryed for local interfaces .. and i get class class exception .. for EJBHome ... if i say EJBLocalHome then in that case the EJBMetadata is NOT available ..
    So what should i do ??
  22. Hi Everyone,
    Has anybody found out the way to do this for dynamically invoking EJBLocalHome objects? Coz this approach works only for Remote home & remote objects.

    Would appreciate if someone could share his/her findings....

    Btw, Stenilo, the problem is not with runnig pojo's to access EJB's...I have got that up and running for looking up EJBs the traditional way...the problem comes when using this reflection method in a pojo to lookup the ejb.

    byw for now.
  23. Hello again.
    In case of Local,its simpler.
    i have developed one JSP to confirm it.Pasting here the code.
    [ BTW,i dont know,but can we ATTACH some source files with our would be a nice feature for TSS..]

    <%@ page import = "javax.naming.*,java.util.*,*,*,*,javax.ejb.*,java.lang.reflect.*" %>
    <%! public static Object invoke(Class c,Object obj,String mname,Object[] plist){
          Method[] methods = c.getMethods();
          String name=null;
          Object r= null;
          try {
              for(int i = 0; i<methods.length ;i++) {
                 name = methods[i].getName();
                 if(name.startsWith(mname)) {
                    r = methods[i].invoke(obj,plist);
          } catch(Exception e){
          return r;
    Context context= new InitialContext();
    String jndi = "TheLOOOOOOOOOOOOCALHOME";
    Object obj = context.lookup(jndi);
    System.out.println("Looked Up");
    EJBLocalHome lhome = (EJBLocalHome) obj;
    System.out.println("Looked Up");
    //invoke create
    EJBLocalObject lobj =(EJBLocalObject) invoke(obj.getClass(),obj,"create",null);
    Boolean res = (Boolean)invoke(lobj.getClass(),lobj,"sayHELLO",null);


  24. Hey Vimarsh, nice one...though upon reflecting(mentally) back on the code for locating a remote service, why should I need to use the EJBMetaData to get to know the RemoteInterface class.

    EJBMetaData md = this.theHome.getEJBMetaData();
    Class homeClass = md.getHomeInterfaceClass();

    For remote services too, what if we take the same approach as we take during invoking local services, as u have implemeted in ur jsp?

    //invoke create
    EJBLocalObject lobj =(EJBLocalObject) invoke(obj.getClass(),obj,"create",null);

    This invocation of "create" on the home class, should always return back to u either an EJBRemoteObject OR an EJBLocalObject...

    EJBObject lobj =(EJBObject) invoke(obj.getClass(),obj,"create",null); --> For Remote services

    EJBLocalObject lobj =(EJBLocalObject) invoke(obj.getClass(),obj,"create",null); --> For Local services

    Or alternatively, why not just cast it to an Object instead of an EJBXXXObject?

    Object lobj =(Object) invoke(obj.getClass(),obj,"create",null);
    Boolean res = (Boolean)invoke(lobj.getClass(),lobj,"sayHELLO",null);

    Why bother about if it is a remote service or a local service...I could have this code sitting in a common delegate object, which just invoked a given method on the given service (which could be a local EJB or a remote EJB)...but the client does not need to know about it and neither does the delegate....

    Am I overlooking something here? coz this seems just a bit toooo easy for comfortability...

    take care
  25. valid argument.
    can you test and paste the results.
  26. Hi Vimarsh and everybody,
    I used this reflection method in my application (a Business Rules engine) and it works great! I am using Websphere 5.0 with WSAD 5.0.

    It works when I invoke the ejb from a local client like another Session bean or probably a servlet which is running in the web container of WAS itself. I will be testing it soon with another WEb Container...

    But the moment I run it from a standalone client (pojo) via the Websphere --> Run As option OR command line, it throws me this exception:

    java.rmi.MarshalException: CORBA MARSHAL 0x4942f89a No; nested exception is:
    org.omg.CORBA.MARSHAL: Unable to read value from underlying bridge : my.testbed.ejb.ChildBean minor code: 4942F89A completed: No
    org.omg.CORBA.MARSHAL: Unable to read value from underlying bridge : my.testbed.ejb.ChildBean minor code: 4942F89A completed: No
    at org.omg.stub.javax.ejb._EJBHome_Stub.getEJBMetaData(
    at my.testbed.ReflectnEjbClient.<init>(
    at my.testbed.ReflectnEjbClient.main(

    It happens at the time of getting the Meta Data information:

    EJBMetaData md = this.theHome.getEJBMetaData();

    Now I know there is a problem with Websphere, wherein a standalone java client cannot easily lookup an enterprise bean unless it is running in the same WAS enviornment! But I have found out the way to do that for standard lookups and ejb invocations & its pretty simple.

    I am not sure if the above Marshalling problem is related to it....any thoughts guys?
  27. Hello Pravin,

    I had similar problems in the past when I was trying to use standalone Java applications as clients to my J2EE apps on WSAD. Try to change your WSAD JRE to be the same as your test environments's JRE. Go to Window->Preferences->Java->Installed JREs and add the location to your test envrironment's JRE. This should be %WSAD4_ROOT%\runtimes\base_v5\java\jre then select it as the default. Hope this works for you :-)
  28. Very neat!!...but one caveat...[ Go to top ]

    Hi Stelios Psarras,

       I do have similar problem where getEJBMetaData() & then getHomeInterfaceClass() is not being identified.

      I'm deploying in WL5.1 Can u help me to solve this issue of identifying the methods

    Thnx in Advance
  29. other use for this[ Go to top ]

    I use this for a completely different reason. Please let me know whether or not this is a good use. I use it to contact a session bean on another appserver on the same machine. To increase performance in regard to reflection the client is a singleton, which has most of its code in the constructor, only the invoking of the method is in an instance method. The reason to use it was to avoid having to patch the app. server of the client, each time the EJB changes (which happens quite often).

    The strange thing now is that this client works when run from a main method on my computer, but it won't work on the application server. It's exactly the same code, and the classpath is also identitical. Help would greatly be appreciated. This is the stacktrace :

    weblogic.utils.AssertionError: ***** ASSERTION FAILED *****[ Unable to load home class: java.lang.ClassNotFoundException: be.egov.usermgmt.ejb.UserMgmtBaseHome ]
            at weblogic.ejb20.internal.EJBMetaDataImpl.getHomeInterfaceClass(

    The line that causes the error is :

          Class homeClass = ejbMetaData.getHomeInterfaceClass();

    So to sum it up , 2 questions :

    * Is this a good use of this strategy ?
    * What could cause this error ? security ? the stacktrace doesn't give me a lot of info
  30. How do we implement the strategy using local home interfaces?
  31. I could implement succefully this pattern defining an interfase that specify a getLocalInterfaseClass method implemented on a LocalEJBBean Class an LocalInterfase, and using reflection to find a specified method on the EJBLocalObject returned.

  32. I was able to achieve it too. Just kept all my stuff (jndiName for EJB, tx attribute etc.) at a meta-level (an XML), read everything from there and used reflection to invoke the appropriate method.
  33. in Business Delegate Pattern[ Go to top ]

    Hi i m using business delegate pattern with Struts.
     Structure is: ->
     Action class(Strut's Action) -> business Delegate -> ejb...

    public final class My extends Action
     Collection c = myBusinessDelegate.getData(ID);

    public class MyBusinessDelegate
       public Collection getData(Long id) throws Exception {
    Collection retVal = null;
    retVal = getContactsSessionRemote().getCityByCriteria(cad);
    // return retVal;
    // }
  34. in Business Delegate Pattern[ Go to top ]

    Hi i m using business delegate pattern with Struts.
     Structure is: ->
     Action class(Strut's Action) -> business Delegate -> ejb...

    public final class My extends Action
     // call the BusinessDelegate Method.....
     Collection c = myBusinessDelegate.getData(ID);

    public class MyBusinessDelegate
       public Collection getData(Long id) throws Exception {

    // call the Session Bean method...


    plz tell me how use the Java reflection in this Scenario
    how to create a dynamic delegate as a run time...and call the session bean method....

  35. Hi All,

       I am wondering if this works on invoking EJB on a different machine.Technically as per my knowledge it should work. I want to use this Idea for acheiving the following task.Please give your feedback.

       We are developing a Messaging Service to use in our Intranet by numerous applications (J2EE,.NET and legacy).Just like the one offered by amazon.

       I don't want the clients to my service, to bind their MDB to my queues.Insted they subscribe to a particular queue through the interface provided by me (Stateless session bean) giving classname and method to be invoked incase a message to that queue, and when there is a message for their queue , I will call the method they interested from their classes using reflection and the above strategy.

    Please letme know what you think.

    - Giri
  36. Hi Everybody,

    With due credit to the author of this post, the strategy to lookup and invoke EJB's is good.
    I have worked on similar problems with similar solution previously and my experience is bit more mixed. In some of my previous projects I had used similar approach to solve the repeated lookup and invocation of the EJB, during which I came across a common problem, here is a small description of it.

    The strategy used above works perfectly fine mostly in cases of stateless session beans (SSB).
    The problem gets a bit more complicated with we are handling a Stateful Session Beans, since the create method of a Stateful session beans could take parameters and different stateful session beans could have different create method construct, this kind of becomes a hurdle when u try to create the Remote object using the home object that we obtain after look up and narrowing process.

    The above problem applies for Entity beans as well.

    What we were planning in one of our previous project was give on generic implementation of a EJB lookup, narrowing and creation which was not possible 100% coz of the different create method constructs.

    One could say we can overload the method which does the lookup, narrowing and creation method (say in a service locator) to take the initialization parameter in case of Stateful session beans and Entity beans.


    Another approach is using dynamic proxies, which are also are limited by the same problem with the different constructor signature, unless you end up writing/generating dynamic proxy classes (which does the lookup, narrowing and creation of remote object) for every EJB.

    MY PERSONAL OPINION is we can use the approach of reflection in most of the cases say 60% max, but can't use it in rest without a bit of tweaking !!!!

    I would be interested in hear what other think about it. I would appreciate any input regards to this.

    Thanks and Cheers !!!!
    Madhusudan M Krishnamurthy
  37. Hi,

    I see the adavantage of flexibility with this pattern of invoking EJB's by reflection.

    But what about the performance impact?.
    (Cause as Reflection if I am wrong is slow)