次のように機能するEJBファクトリクラスを作成しようとしています。引数としてEJBのクラスを受け取るメソッドがあり、EJBにリモートインターフェイスがあるかどうか(例外をスローしない場合)と、します、それは関係するEJBを返します。
以下のコードはまさにこれを行います。ただし、返されるオブジェクトは、関連するBeanのリモート・インターフェースのタイプであり、Bean自体のタイプではありません。どうすればこれを変更できますか?ジェネリック型Tがメソッドに渡されるクラスと同じ型であることをJavaに伝える方法はありますか?
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;
}
}
Factoryを使用した単体テストの例。
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で機能しますが、他のアプリサーバーではテストしていません。