views:

56

answers:

2

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.

+3  A: 

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.

pitpod
Thanks, this answers all I wanted to know.
Josh Meredith
The class don't have to be on the classpath on start, you can define an own ClassLoader to load classes at runtime. But you're right, OSGI already does all that is needed.
Mnementh
+1  A: 

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

Daniel