开发者

How to instantiate a class, either EJB or POJO?

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

public Object instantiate(Class c) {
  return /* ... */
}


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)


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜