0

I have a list of classes which I need to use many times during the execution of my program, I need to load them dinamically because their code can change very often and I want to treat them as services so that I can update them easily. Here my questions:

Does UrlClassLoader always load the class again even when it hasn't changed? Can this cause performance or memory issues?

Here is my code for testing this:

package classloader;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class ClassLoaderClass {
    public static void main(String[] args) throws ClassNotFoundException, MalformedURLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InterruptedException {

            //no paramater
            Class noparams[] = {};

        URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL("file:///C:/Users/hm/Documents/classes/")});
        Class gsonClass = urlClassLoader.loadClass("AppTest");
        Constructor constructor = gsonClass.getConstructor();
        Object Apptest = constructor.newInstance();
        Method method = gsonClass.getMethod("printIt",noparams);
        Object returnObj =  method.invoke(Apptest, null);
        String jsonString = (String)returnObj;
}

}

I hope you can help me, thanks.

Hira
  • 3
  • 2
  • Have you considered using OSGi, which has fairly robust support for loading/stopping "bundles" allowing code to change at runtime? – Brett Okken Jun 22 '14 at 12:34
  • that seems useful but I have a very complex aplication and im looking for something that I can add to my app to make it work with some classes as services. It seems to me that for using OSGI i'd have to program all my application again and i dont want that, pls correct me if im wrong – Hira Jun 22 '14 at 13:00

1 Answers1

0

URLClassLoader checks if a class has already been loaded and doesn't load it again. See ClassLoader.loadClass() for details.

kaetzacoatl
  • 1,419
  • 1
  • 19
  • 27
  • so that means that if i change the code of a class after loading it those changes wont be loded? if so, how can I reload the class only when something has changed? – Hira Jun 22 '14 at 13:41
  • @Hira you have to redifine your class, but I'm not sure how to access [ClassLoader.defineClass()](http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html#defineClass%28java.lang.String,%20byte[],%20int,%20int%29) – kaetzacoatl Jun 22 '14 at 13:53