Including Java Classes and Running Them at Runtime

I have a Java project that needs an "addon" interface. I was thinking about loading some class files that have default methods such as initialize()

and shutdown()

that will be called after the class has been loaded into the application. Is this the way to do it? How can I approach this problem?

0


a source to share


5 answers


Look at the class Class , in particular forName , which allows you to refer to a class by name. Any class in the path can be loaded as follows. Whether a reboot is possible, I don't know.



In any case, every class you want to load dynamically must implement its own user interface AddOn

, thus implementing initialize

and shutdown

.

+3


a source


You will need first ClassLoader

; you can get the current s getClass().getClassLoader()

, but then your addon classes must be on the classpath. You might want to create a custom classloader that looks for your addons directory.



Once you get it ClassLoader

, you can use it to load the class . This gives you an Class

object; you can use reflection to call the method initialize()

if present.

+1


a source


If you look at something a little more complex you can try: http://jpf.sourceforge.net .

... JPF provides an execution engine that dynamically detects and loads "plugins". A plugin is a structured component that describes itself in JPF using a "manifest" ....

+1


a source


Another nice way to implement addons is with java.util.Serviceloader . Take a look at the javadocs, they explain the principle.

0


a source


public class SomeClass { 
    static {
        System.out.println("Being called with the class is loaded");
        initialize();
    }
    static void initialize(){}
}

      

Is that your question?

-1


a source







All Articles