HelloEJBRemote.java
package com.service;
import javax.ejb.Remote;
@Remote
public interface HelloEJBRemote {
public String RemoteSayHello(String name);
}
HelloEJB.java
package com.service;
import javax.ejb.Local;
@Local
public interface HelloEJB {
public String sayHello(String name);
}
HelloEJBImpl.java
package com.serviceImpl;
import javax.ejb.Stateless;
import com.service.HelloEJB;
import com.service.HelloEJBRemote;
@Stateless
public class HelloEJBImpl implements HelloEJBRemote,HelloEJB {
@Override
public String sayHello(String name) {
return name+" say:HelloEJB";
}
public String RemoteSayHello(String name) {
return name+" (Remote)say:HelloEJB";
}
}
EJBClient.java
package com.client;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.service.HelloEJBRemote;
public class EjbClient {
public static void main(String[] args) throws NamingException {
Context ctx = new InitialContext();
HelloEJBRemote he = (HelloEJBRemote)ctx.lookup("HelloEJBImpl/remote");
System.out.println(he.RemoteSayHello("张三"));
}
}
运行报错如下:
Exception in thread "main" java.lang.ClassCastException: $Proxy2 cannot be cast to com.service.HelloEJBRemote at com.client.EjbClient.main(EjbClient.java:12)
求解决!(就剩这么多分了,唉。。。)
------最佳解决方案--------------------------------------------------------
你去远程调用Jboss服务器上的EJB,需要使用Jboss服务器上的JNDI,参数需要你根据自己的情况修改一下:
Hashtable environment = new Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
environment.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
environment.put("java.naming.provider.url", "jnp://www.aaa.com:1099");
InitialContext ctx = null;
try {
ctx = new InitialContext(environment);
System.out.println("ctx.lookup(WorkListManager):==========" + "WorkListManager");
Object obj = ctx.lookup("java:comp/env/ejb/bnsbase/Role");
Role = ((RoleHome) PortableRemoteObject.narrow(obj, WorkListManagerHome.class)).create();
} catch (NamingException ex) {
System.err.println(" ex1: " + ex);
}