Java call plugin class

How can I call a class in Java when the class name will not be known at compile time (for example, if it was a plugin). For example, the user selects a plug-in from the GUI (Java class), the application then creates a new instance of the class and calls one of its methods (the method name will be known at compile time (for example, "moduleMain"))).

Thanks for any input.

+3
source share
2 answers

The old-style solution for this problem is to define an interface that all plugins should implement. Then use Reflection to load this class and apply it to the interface. If an exception does not occur, you can now safely call the method from the interface. This approach has the disadvantage that the class must be accessible in the class path at the beginning of the application.

A more “modern” and dynamic approach to plugins in the Java OSGI world . Eclipse uses OSGI for its plugin system and allows you to add and remove plugins at runtime.

+4
source

I doubt that you want to implement the entire OSGi specification. Use reflexes faster than official dogma says, and it's pretty simple.

: java.sun.com : HardCore Java

+2

Source: https://habr.com/ru/post/1738921/


All Articles