This example shows how a service implementation can be loaded with a URLClassLoader.
The files.
HelloService.java:
public interface HelloService {
public void sayHello();
}
HelloServiceImpl.java:
public class HelloServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("Hello!");
}
}
ServiceFactory.java uses URLClassLoader to load the service implementation:
import java.io.*;
import java.net.*;
public class ServiceFactory {
private static URL[] classLoaderUrls;
public static void setURLs(URL[] urls) {
classLoaderUrls = urls;
}
public static HelloService getHelloService() throws Exception {
URLClassLoader loader = new URLClassLoader(classLoaderUrls);
return (HelloService) Class.forName("HelloServiceImpl", true, loader).newInstance();
}
}
Test.java:
import java.io.*;
import java.net.*;
public class Test {
public static void main(String[] args) throws Exception {
ServiceFactory.setURLs(new URL[] {
new URL("file:service.jar")
});
HelloService h = ServiceFactory.getHelloService();
System.out.println("Class Loader: " + h.getClass().getClassLoader());
h.sayHello();
}
}
Create a runnable client jar:
C:\>jar -cfe client.jar Test Test.class ServiceFactory.class HelloService.class
Create a service jar:
jar -cf service.jar HelloServiceImpl.class
Test:
C:\>java -jar client.jar
Class Loader: java.net.URLClassLoader@addbf1
Hello!
URLClassLoader
最新推荐文章于 2021-07-18 11:06:54 发布