Search code examples
javaandroidclassloader

Loading a remote Java class


I built an android app.

I use an advertising platform, but I'm not sure I would like to stick to it (maybe I'll decide to change it later).

For this purpose, I would like to create an interface, and a class implementing it, calling the ads of the platform.

The idea is that I could later at some point, load another class file from my server (with reflection) replacing the previous one. That way, I will be able to change advertising platform "on the fly" (for instance - Admob/Airpush).

Does someone know how can I load remote classes with Java?

Do you have any code example the shows it?


Solution

  • You need to create your own ClassLoader, give a look at How to use URLClassLoader to load a *.class file?

    Here is an example (from http://www.programcreek.com/java-api-examples/index.php?api=java.net.URLClassLoader, there is others with hosted urls):

    private void invokeClass(String path, String name, String[] args) throws
            ClassNotFoundException,
            NoSuchMethodException,
            InvocationTargetException,
            MalformedURLException,
            InterruptedException,
            IllegalAccessException {
        File f = new File(path);
        URLClassLoader u = new URLClassLoader(new URL[]{f.toURI().toURL()});
        Class c = u.loadClass(name);
        Method m = c.getMethod("main", new Class[]{args.getClass()});
        m.setAccessible(true);
        int mods = m.getModifiers();
        if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
            throw new NoSuchMethodException("main");
        }
        m.invoke(null, new Object[]{args});
        m = null;
        System.gc(); // uh-oh
    }