Java:希望实现将WebService封装到Jar为何加载不到类?

创建工程server

IPrinter

@WebService
public interface IPrinter {
    public String print(String str);
}

Printer

@WebService(endpointInterface = "com.server.IPrinter", serviceName = "Printer")
public class Printer implements IPrinter {
    @Override
    public String print(String str) {
        return "Printing:" + str;
    }
}

Server

 public class Server {
    public void open() {
        try {
            Endpoint.publish("http://localhost:8000/server", new Printer());  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

将工程server打包成server.jar后,通过其他工程加载并发布WebService

 public class Demo {
    public static void main(String[] args) throws Exception {
        URLClassLoader loader = new URLClassLoader(new URL[] { new URL("file:E:\\server.jar") });
        Class<?> clz = loader.loadClass("com.server.Server");
        Method method = clz.getMethod("open");  
        Constructor<?> constructor = clz.getConstructor();  
        Object instance = constructor.newInstance();  
        method.invoke(instance);
        loader.close();
    }
}

报错如下:

 com.sun.xml.internal.ws.model.RuntimeModelerException: 找不到类com.server.IPrinter
    at com.sun.xml.internal.ws.model.RuntimeModeler.getPortTypeName(RuntimeModeler.java:1601)
    at com.sun.xml.internal.ws.model.RuntimeModeler.getPortTypeName(RuntimeModeler.java:1584)
    at com.sun.xml.internal.ws.server.EndpointFactory.create(EndpointFactory.java:226)
    at com.sun.xml.internal.ws.server.EndpointFactory.createEndpoint(EndpointFactory.java:144)
    at com.sun.xml.internal.ws.api.server.WSEndpoint.create(WSEndpoint.java:563)
    at com.sun.xml.internal.ws.api.server.WSEndpoint.create(WSEndpoint.java:545)
    at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.createEndpoint(EndpointImpl.java:308)
    at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(EndpointImpl.java:231)
    at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(ProviderImpl.java:126)
    at javax.xml.ws.Endpoint.publish(Endpoint.java:240)
    at com.server.Server.open(Server.java:8)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.server.Demo.main(Demo.java:15)

无头绪......

2个回答

classpath是否包含server.jar

u011605971
一筐愿望 没有的,但是已经通过URLClassLoader加载了这个JAR还需要classpath也加载一遍吗?谢谢:)
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!