Question

I want to implement an application which could use users implemented classes. Each class should be implemented an interface that I define the interfaces and at last, all of classes which implemented by a user, archived in a jar file. Users copy the jar files in to class path and then only give the jar file name to my application. My application should be able to load jar file dynamically. To do this I found this post that is very useful, but it loads classes by class names. I want to load classes based on their parents.

public class A implements iA {
    @Override
    int getAValue() { ... }
}

public class B implements iB {
     @Override
     int getBValue() { ... }
}

Suppose loaded jar file has both A and B classes. I want to get an instance from class B by knowing the iB interface name.

What should I do?

Was it helpful?

Solution

Check this post out: Find Java classes implementing an interface

It talks about the solution to what you want.

I know what I am going to suggest is not the lightest way to do it, but you just described one of the fundamental use cases for a plugin architecture in Java and the success story of OSGi.

I would suggest using something light like Apache Felix, make the jar that the user provides implement a simple osgi.BundleActivator and register the implementation of your Interface as an OSGi service. (This is just a fancy hash map and nothing to do with REST services or the like).

Then you can just obtain all the implementations of a given interface. Its pretty straight forward. You can check out the Felix documentation here: http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top