Call plugin class in Java
How can I call a class in Java, when the name of the class won't be known at compile time (such as if it were a plugin). For example, from a GUI, a开发者_运维问答 user selects a plugin (a Java class), the application then creates a new instance of the class, and calls one of its methods (the method name would be known at compile time (e.g. "moduleMain")).
Thanks for any input.
The "old style" solution to this problem would be to define an interface that all plugins must implement. Then use Reflection to load this class and cast it to the interface. If no exception occured you can now safely call the method from the interface. This approach has the disadvantage that the class must be available on the classpath at the start of the application.
The more "modern" and dynamic approach to plugins in the Java world is OSGI. Eclipse uses OSGI for its plugin system and allows the addition and removal of plugins during the runtime.
I doubt you want to implement all OSGi spec., use reflections it's faster than official dogma says and it's quiet simple.
See: java.sun.com tutor about reflections And the book: HardCore Java
精彩评论