0

I want to load dynamic library where classes inherit from an interface/abstract class on my core project, so I can load my classes at runtime and use it. How can i do that ?

Example:

Core: ITrigger (interface)

Library: {MyTriggerOne extends ITrigger} {MyTriggerTwo extends ITrigger}

jrbedard
  • 3,662
  • 5
  • 30
  • 34
liege30
  • 11
  • 3

3 Answers3

0

If you want to load a class/library dynamically use Class.forName('class name') method to load.

Upesh M
  • 382
  • 1
  • 4
  • 9
  • Yes, but the class name are not the same, so how could i load classes dynamically without the classname known – liege30 Dec 08 '16 at 09:47
  • Without knowing the classname it will be difficult. One solution is to load the entire library/jar using Class.forName and then using reflection identify the class which implements your interface, then create an instance of that class. – Upesh M Dec 08 '16 at 09:55
  • If i load the entire jar using Class.forName, my jar become a "class" and my classes inside the jar becomer "inner classes" ? – liege30 Dec 08 '16 at 10:00
  • use this solution to load your class from jar http://stackoverflow.com/questions/11016092/how-to-load-classes-at-runtime-from-a-folder-or-jar – Upesh M Dec 08 '16 at 10:40
0

Java's SPI(Service Provider Interface) libraries allow you to load classes dynamically based on the interfaces they implement, that can be done with the help of META-INF/services.

You can create a interface like

package com.test.dynamic;
public interface ITrigger {
    String getData();
    String setData();
}

you can use the ServiceLoader class to load the interface like below code

ServiceLoader<ITrigger> loader = ServiceLoader.load(ITrigger.class);

then you can perform all the operation on it. If you have some other implementing classes on your classpath, they register themselves in META-INF/services. you need to create a file in META-INF/services in your classpath with the following properties

  1. The name of the file is the fully qualified class name of the interface, in this case, it's com.test.dynamic.ITrigger

  2. The file contains a newline-separated list of implementations, so for the example implementation, it would contain one line: com.test.dynamic.impl.SomeITriggerImplementation class.

mohan rathour
  • 420
  • 2
  • 12
0

I had the same requirement and I used the library Reflections.

Very simple code snippet:

public Set<Class<? extends ITrigger>> getITriggerClasses() {
    final Reflections reflections = new Reflections("package.where.to.find.implementations");
    return reflections.getSubTypesOf(ITrigger.class);
}

Then you can use the method Class::newInstance to create the ITrigger(s). This is a very simple example, there are several options to initialize the Reflections class (not only with one package name).

Bastien Aracil
  • 1,531
  • 11
  • 6