Question

I have a class, which is either EJB or POJO (I don't know). I have to make an instance of this class. Is there any pattern for this operation? Or I should manually check for EJB annotations and then do JNDI lookup?

public Object instantiate(Class c) {
  return /* ... */
}
Was it helpful?

Solution

EJB classes should be instantiated only by the container. Otherwise they are not EJB. If you want to obtain an EJB instance, look it up via JNDI, or inject it.

You can see if a class is supposed to be an EJB by verifying its annotations:

if (clazz.isAnnotationPresent(Stateless.class)
   || clazz.isAnnotationPresent(Statefull.class)) { .. };

(and message-driven, perhaps)

OTHER TIPS

POJO (Plain Object Java Object) is normall instantiated with the new operator.

MyClass myClass = new MyClass( args )

It can also be created via reflection.

MyClass myClass = MyClass.class.newInstance();

Yes, you will need to check for EJB3 annotations and somehow figure out what it's JNDI name is (which may depend on your container).

The Seam framework does this using a JNDI name pattern (see the seam documentation). This way the Seam contexts can have a mix of POJOs and EJBs in them.

EJB3 is almost POJO that definitely has default constructor. There is no problem to instantiate it. The same is about any class that have default constructor.

Just say

clazz.newInstance();

and you are done.

If you are writing method that creates instances of any class this method should be parametrized:

public <T> T instance(Class<T> clazz)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top