JAVA:从外部类中获取.class

时间:2016-04-18 11:07:04

标签: rest jar jersey classloader external

我尝试从外部JAR加载一个类。这是泽西岛的servlet。要将servlet添加到Servlet容器,我将调用Jersey应用程序类。但是无法从浏览器访问资源。我需要来自外部加载类的.class,但是如何?

public class ApplicationConfig extends Application {

    private Object external;

    public ApplicationConfig() {
    }

    @Override
    public Set<Class<?>> getClasses() {
        String pathToJar = someJAR;
        try {
            JarFile jarFile = new JarFile(pathToJar);
            Enumeration enumeration = jarFile.entries();

            URL[] urls = { new URL("jar:file:" +pathToJar+"!/")};
            URLClassLoader cl = URLClassLoader.newInstance(urls);
            while(enumeration.hasMoreElements()){
                JarEntry je = (JarEntry) enumeration.nextElement();
                if(je.isDirectory() || !je.getName().endsWith(".class")){
                    continue;
                }
                String className = je.getName().substring(0,je.getName().length()-6);
                className = className.replace("/",".");
                if(className.contains("HelloWorldServlet")) {
                    System.out.println(className);
                    external = cl.loadClass(className).newInstance();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        Set<Class<?>> classes = new HashSet<>();
        classes.add(HelloServlet.class);
        classes.add(external.getClass().getClass());

        return super.getClasses();
    }
}

public class ApplicationConfig extends Application {

    private Class<?> external;

    public ApplicationConfig() {
    }

    @Override
    public Set<Class<?>> getClasses() {
        String pathToJar = someJAR;
        try {
            JarFile jarFile = new JarFile(pathToJar);
            Enumeration enumeration = jarFile.entries();

            URL[] urls = { new URL("jar:file:" +pathToJar+"!/")};
            URLClassLoader cl = URLClassLoader.newInstance(urls);
            while(enumeration.hasMoreElements()){
                JarEntry je = (JarEntry) enumeration.nextElement();
                if(je.isDirectory() || !je.getName().endsWith(".class")){
                    continue;
                }
                String className = je.getName().substring(0,je.getName().length()-6);
                className = className.replace("/",".");
                if(className.contains("HelloWorldServlet")) {
                    System.out.println(className);
                    external = cl.loadClass(className);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        Set<Class<?>> classes = new HashSet<>();
        classes.add(HelloServlet.class);
        classes.add(external);

        return super.getClasses();
    }
}

不能工作。

有办法搞定吗?

我想从Servlet容器中的JAR动态加载REST端点。

0 个答案:

没有答案