我正在尝试创建一个 EJB 工厂类,它的工作原理如下:您有一个方法将 EJB 的类作为参数,然后它检查 EJB 是否具有远程接口(如果没有抛出异常)以及它是否确实,它返回相关的 EJB。
下面的代码正是这样做的。然而,它返回的对象是相关 bean 的远程接口类型,而不是 bean 本身的类型。我怎样才能改变这个?有没有办法告诉 Java 泛型类型 T 与传递给方法的类的类型相同。
import java.util.Properties;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.naming.*;
public class EJBFactory
{
private InitialContext ctx;
public EJBFactory() throws NamingException {
ctx = new InitialContext();
}
public EJBFactory(String host, String port) throws NamingException {
Properties props = new Properties();
props.setProperty("org.omg.CORBA.ORBInitialHost", host);
props.setProperty("org.omg.CORBA.ORBInitialPort", port);
ctx = new InitialContext(props);
}
.
// To improve: The object returned should be of the type ejbClass
// instead of the remote interface, which it implements
public <T> T createEJB(Class ejbClass) throws NamingException
{
Class remoteInterface = null;
for(Class interface_: ejbClass.getInterfaces()) {
if(interface_.isAnnotationPresent(Remote.class))
remoteInterface = interface_;
}
if(remoteInterface == null)
throw new IllegalArgumentException(
"EJB Requires a remote interface");
// Get the stateless annotation, then get the jndiName
Stateless stateless =
(Stateless)ejbClass.getAnnotation(Stateless.class);
String jndiName = stateless.mappedName();
T ejbObj = (T) ctx.lookup(jndiName);
return ejbObj;
}
}
使用工厂的单元测试示例。
import junit.framework.TestCase;
public class SimpleEJBTest extends TestCase
{
TestRemote testBean;
@Override
protected void setUp() throws Exception {
super.setUp();
EJBFactory ejbFactory = new EJBFactory();
testBean = ejbFactory.createEJB(TestBean.class);
}
public void testSayHello() {
assertEquals("Hello", testBean.sayHello());
}
}
注意:该示例适用于 Glassfish,我没有使用任何其他应用服务器对其进行测试。