如何实例化一个类,EJB 或 POJO?

发布于 2024-10-04 17:42:21 字数 174 浏览 0 评论 0 原文

我有一个类,它要么是EJB,要么是POJO(我不知道)。我必须创建这个类的一个实例。这个操作有什么模式吗?或者我应该手动检查 EJB 注释,然后进行 JNDI 查找?

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

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 /* ... */
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我要还你自由 2024-10-11 17:42:21

EJB 类只能由容器实例化。否则它们就不是 EJB。如果您想获取 EJB 实例,请通过 JNDI 查找它,或者注入它。

您可以通过验证类的注释来了解该类是否应该是 EJB:(

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

也许还有消息驱动的)

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)

给妤﹃绝世温柔 2024-10-11 17:42:21

POJO(普通对象 Java 对象)通常使用 new 运算符实例化。

MyClass myClass = new MyClass( args )

它也可以通过反射创建。

MyClass myClass = MyClass.class.newInstance();

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();
游魂 2024-10-11 17:42:21

是的,您需要检查 EJB3 注释并以某种方式找出它的 JNDI 名称(这可能取决于您的容器)。

Seam 框架使用 JNDI 名称模式来完成此操作(请参阅 接缝文档)。这样,Seam 上下文中就可以混合使用 POJO 和 EJB。

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.

半﹌身腐败 2024-10-11 17:42:21

EJB3几乎是肯定有默认构造函数的POJO。实例化没有问题。对于任何具有默认构造函数的类来说也是如此。

只要说出来

clazz.newInstance();

,你就完成了。

如果您正在编写创建任何类的实例的方法,则应对该方法进行参数化:

public <T> T instance(Class<T> clazz)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文