views:

53

answers:

2

Is there a ClassLoader implementation I can use to load classes from an InputStream?

I'm trying to load a JAR for which I have an InputStream into a new ClassLoader.

+3  A: 

This is unlikely, as you will find if you try to do it yourself. You won't be able to randomly access an InputStream to look up classes as they're requested, so you'll have to cache the contents either in memory or in the file system.

If you cache on disk, just use URLClassLoader.

If you cache in memory, you'll need to create some sort of Map with JarInputStream and then extend ClassLoader (overriding the appropriate methods). The downside of this approach is that you keep data in RAM unnecessarily.

McDowell
A: 

I know this is not really an answer to your question regarding JAR/InputStream. But following may be an alternative solution to what you are trying to achieve. Here is some code that will add a URL to classpath.

You may convert a java.io.File to URL as f.toURI().toURL()

        /**
         * Adds a URL to current classpath.
         * @param url url
         */
        public static void addURL(URL u) {      
                URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
                try {

                        Method method = URLClassLoader.class.getDeclaredMethod("addURL",parameters);
                        method.setAccessible(true);
                        method.invoke(sysloader,new Object[]{u});
                        System.out.println("Dynamically added " + u.toString() + " to classLoader");
                } 
                catch (Exception e) {
                        e.printStackTrace();
                }
        }
ring bearer